ArrayList<String> vs String[], How and when to use? - java

I am learning about making a ListView on Android app, and I want to know about these two, some examples use String[], and some use ArrayList....but I dont see how people adding more item in String[].

String[] is a primitive data type, a plain simple array with a fixed size which has to be known at COMPILE TIME and can't be changed at RUNTIME.
Consider:
String[] foo = new String[2];
Here you declare a simple string array which can hold 2 strings.
Let's add stuff to it:
foo[0] = "String One";
foo[1] = "String Two";
You can also forward declare it like that:
String[] foo = {"String One", "String Two"};
You can change the contents of foo but you can't add another string nor remove it since it has a fixed size.
At the other hand, ArrayList is a dynamic list where you can add or remove items of type T at any time in your program.
The size does not need to be defined at COMPILE TIME and the contents of a Arraylist can be added or removed at RUNTIME . It is the most flexible data structure of the two.
Consider:
ArrayList<String> foo = new ArrayList<>();
That declares the dynamic array. It has a variable size and there is no need to define the number of elements upon initalisation. You can add or remove elements to/from it as you like, any time at RUNTIME.
Note that:
foo.add("String One");
foo.add("String Two);
can be added at any time in your program. Same goes for removing elements. Since ArrayList is a (generic) class, it has also a bunch of helpfull methods that a plain array does not have !
Please also read about Java generics to get the full picture.
So it depends what you want to do with the ListView. If you just want to have a fixed set of strings displayed then go for String[], or you need to change the content of the view dynamically by adding or removing data, then an ArrayList might be the right one for the job.

First of all, The String[] is belong to the conventional array which means that this data size that the array is contained is fixed and cannot be changed. Otherwise, the ArrayList is not. It can grow the size as the number elements grows. Moreover, ArrayList has a set of methods to access elements and modify them. But, the ArrayList just can store Object and the storing speed is more slower.
For the answer why in a ListView or RecyclerView, most of cases, we use the ArrayList instead of Array because of the ability of extension in ArrayList. For example, in the NoteApp, if you use the Array, you must set the fixed allocate numbers for the notes, but if you adding the new note, you must change it programmatically. It cannot adapt the size to contain the new note. So that, the ArrayList is suitable for this case.

Related

How to efficiently make Wrapper for MT20x Message

I planned to make a wrapper to Swift MT203, MT204 messages.
Message Structure as follows,
MT203 -
2 Mandatory Sequences, where first one exists once and second one can exists two to ten times, and each sequence can contains mandatory fields and optional fields.
MT204 -
2 Mandatory Sequences, where first one exists once and second one can exists more than one time, and each sequence can contains mandatory fields and optional fields.
[References for the MT203 and MT204]
https://www2.swift.com/knowledgecentre/publications/usgf_20180720/1.0?topic=finmt203.htm
https://www2.swift.com/knowledgecentre/publications/usgf_20180720/1.0?topic=finmt204.htm
Which data structure is better to use to store the second sequences in each cases,
I prefer, Array for instance MT203, since I know the maximum size of second sequence but for MT204 I was confused to choose which is better from array and array list.
As during unpacking we have to get fields continuously but not all fields are mandatory for the second sequences.
[Also do comment if the first one choice of Array is not valid]
I think you'd do quite fine with either data structures.
Having said that, there's some things you might want to consider: you can make an ArrayList (like any other list) Immutable. That will prevent unwanted modification of the contents. This might be very interesting when you pass these message objects around and want to prevent someone else to modify the message accidentally. There's many ways to make a list immutable - such as Collections.immutableList(myArrayList) or Guava's ImmutableList.copyOf(myArrayList).
Having said that, I believe that there are more important considerations than features of lists over features of array:
First of all, I would consider having them both use the same data structure - especially if both messages are used in the same part of the codebase, it's going to be very confusing if one message type is an array, while the other one is a list. This might ultimately become a pain in the back as both messages will have to be handled differently. e.g. if you want to log messages - you'll have to do that differently for lists vs arrays.
Secondly, I would recommend, modelling each of these messages as a class. That class would (obviousely) use an array or a list internally to store the message data, but it would also give higher level semantical access to the contents of the message.
say you wanted the ValueDate of MTS203 (field index 1): you'd always need to call dateFormat.parse(message[1]) for that - and everyone would need to remember what index 1 was and how to parse the date string into an actual date object. If you had a class like this:
class MultipleGeneralFinancialInstitutionTransfer {
private List<String> messageData;
/** constructor... */
public Date getValueDate() {
return parseDate(messageData.get(1)); // imagine parse date being a method to parse the actual format
}
}
it would be much more convenient to work with that message - and nobody would need to remember the actual format of that message.
I. Size: Array in Java is fixed in size. We can not change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically.
II. Performance: In Java Array and ArrayList give different performance for different operations.
add() or get(): Adding an element to or retrieving an element from an array or ArrayList object has similar performance. These are constant time operations.
resize(): Automatic resize of ArrayList slows down the performance. ArrayList is internally backed by an Array. In resize() a temporary array is used to copy elements from old array to new array.
III. Primitives: Array can contain both primitive data types as well as objects. But ArrayList can not contain primitive data types. It contains only objects.
IV. Iterator: In an ArrayList we use an Iterator object to traverse the elements. We use for loop for iterating elements in an array.
V. Type Safety: Java helps in ensuring Type Safety of elements in an ArrayList by using Generics. An Array can contain objects of same type of classe. If we try to store a different data type object in an Array then it throws ArrayStoreException.
VI. Length: Size of ArrayList can be obtained by using size() method. Every array object has length variable that is same as the length/size of the array.
VII. Adding elements: In an ArrayList we can use add() method to add objects. In an Array assignment operator is used for adding elements.
VIII. Multi-dimension: An Array can be multi-dimensional. An ArrayList is always of single dimension
Now you can chose as per your need which is better for you

continuously changing array size [duplicate]

This question already has an answer here:
How to manage Continuous Changing values in an array of strings [closed]
(1 answer)
Closed 9 years ago.
I have an array of strings but the values in array is changing continuously.
Is there any other way of managing the array except removing items and changing index locations?
public String[] deviceId=null;
deviceId=new String[deviceCount];
in my case deviceCount is changes as new device comes.
so i continuously need to change array size and add or remove items
Use ArrayList in place of String[] ..
And you can also easily cast ArrayList to String[] for your final output as
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
You could use a List. It changes size depending on how many objects you put in it.
List<String> list = new ArrayList<String>;
public static void main(String[] args) {
list.add("string 1"); //Add strings to the list
list.add("string 2");
System.out.println(list.get(0)); //Get the values from the list
System.out.println(list.get(1));
}
Instead of using Arrays, you could use ArrayLists. You can add as much as you want to them without having to re-size the array and once you no longer need an item it can be removed. Here is a link to an overview of ArrayLists and some examples using them: http://www.tutorialspoint.com/java/java_arraylist_class.htm
Hope this helps.
If you know the max count of devices. Then you can define an array with max size.
String[] deviceId = new String[MAX_DEVICE_COUNT];
Or else simply go with a List.
List<String> deviceId=new ArrayList<String>();
Don't worry about performance, so much with a array.
- In Java arrays are initialized at the time of its creation whether its declared at class level or at local level.
- Once the size is defined of an array in Java it can't be changed.
- Its better to use Collection like List.
- It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.
- List is an Interface in Java, you can use its concrete sub classes like ArrayList, LinkedList..etc.
Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.

Adding element to next free space in array

I have an array
String[] path={abc,bcd};
I pass this array in a method:
addElement(path);
In method
void addElement(String[] path)
{
// here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
path[path.lenght]="qsd";
}
But this is giving me an error.
I dont want to use an ArrayList.
The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.
This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so
String[] addElement(String old[]){
String arr[] = new String[old.length+1];
//copy all the elements in old...
arr[old.length] = "whatever";
return arr;
}
Then use
path = addElement(path);
You should use ArrayList
Otherwise you have to resize the array by allocating new memory of the size of the original array +1, copy the elements from the old one to the new one, and add in the new element.
You can't change the size of emulated array in GWT (even if javascript arrays support this stuff). You'll have always to create a new instance of array. Most common way to solve this problem is to use one of the collection classes (like java.util.ArrayList) . Example:
ArrayList<String> path = new ArrayList<String>(Arrays.asList("abc","bbc"));
path.add("qsd");

Stuck on creating Java Arrays by not hardcoding the array size

I want to put this which will be in the main method:
int numberOfElements = readFile(args[0],capacities);
the variable numberOfElements is 28.
below is just to let you see a preview of readFile looks like.
private static int readFile (String filename, String[] capacities)
Basically I want to create the string array called capacities using the variable numberOfElements as its array size:
I'm running into problems on how to do that.
If you already know the size of the array when it is created the the following works fine:
String[] capacities = new String[numberOfElements];
But if you think the size may need to change, I urge you to look into ArrayList. It allows you to add a new element at any time and has a decent search.
String[] frobs = new String[numberOfElements];
But why not use a collection?
It looks like you are trying to create an array to hold all the results of readFile, but you don't know how big it needs to be until after it already needs to be created.
What you need to do is either use a List (for example ArrayList) which doesn't need an require that you know the size when you create it. Instead these data structures grow as elements are added to them.
Or you need to write some other function which can read the data file without storing it's values anywhere (perhaps called countFile. All this function would do was count the number of entries you would need in the array in order to hold the data when you actually read and store it using readFile.
Do I misunderstand your question? It should be simply
String[] temp = new String[numberOfElements];

Is it possible to create an open-ended array?

I was wondering if I could create an array without having to enter a value. I don't fully understand how they work, but I'm doing an inventory program and want my array to be set up in a way that the user can enter products and their related variables until they are done, then it needs to use a method to calculate the total cost for all the products. What would be the best way to do that?
Use an ArrayList.
This will allow you to create a dynamic array.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
Here is an example/overview:
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Yes, you can do this. Instead of using a primitive type array, for example new int[10], use something like the Vector class, or perhaps ArrayList (checkout API docs for the differences). Using an ArrayList looks like this:
ArrayList myList = new ArrayList();
myList.add("Item 1");
myList.add("Item 2");
myList.add("Item 3");
// ... etc
In other words, it grows dynamically as you add things to it.
As Orbit pointed out, use ArrayList or Vector for your data storage requirements, they don't need specific size to be assigned while declaration.
You should get familiar with the Java Collections Framework, which includes ArrayList as others have pointed out. It's good to know what other collection objects are available as one might better fit your needs than another for certain requirements. For instance, if you want to make sure your "list" contains no duplicate elements a HashSet might be the answer.
http://download.oracle.com/javase/tutorial/collections/index.html
The other answers already told how to do it right. For completeness, in Java every array has a fixed size (length) which is determined at creation and never changes. (An array also has a component type, which never changes.)
So, you'll have to create a new (bigger) array when your old array is full, and copy the old content over. Luckily, the ArrayList class does that for you when its internal backing array is full, so you can concentrate on the actual business task at hand.

Categories

Resources