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[].
2 Answers
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.
5 Comments
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.