I have searched this, but couldn't find what i need, so i created a new post. I hope to understand about this problem. Thanks.
ArrayList<String> arraylist= new ArrayList<String>();
arraylist.add("Nguyen");
arraylist.add("Viet");
String[] name={"Quan","Doan","Thi","Ha"};
arraylist.add(name);// error here
ArrayList<Object> arraylist1=new ArrayList<Object>();
arraylist1.add("Nguyen");
arraylist1.add("Viet");
Object[] name1={"Quan","Doan","Thi","Ha"};
arraylist1.add(name1);// not error
Can someone explain that when i pass name
into add()
method then I get a error, but when i pass name1
into add()
method, it works fine, why is it so...
An array String[] cannot expand its size. You can initialize it once giving it a permanent size: String[] myStringArray = new String[20](); myStringArray[0] = "Test"; An ArrayList<String> is variable in size.
Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.
arraylist is an ArrayList of String elements, so you can't add an array instance to it. arraylist1 is an ArrayList of Object elements, so you can add an array to it, since an array is an Object .
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
arraylist
is an ArrayList of String elements, so you can't add an array instance to it. arraylist1
is an ArrayList
of Object
elements, so you can add an array to it, since an array is an Object
.
If you wish to add the individual elements of the arrays to the List
s, both add
calls should be changed to addAll
:
arrayList.addAll(Arrays.asList(name));
arraylist1.addAll(Arrays.asList(name1));
arraylist.add(name);// error here
Error because name
is an array. Not a String
. You are trying to add a Array object to an ArrayList which accepts only Strings.
arraylist1.add(name1);// not error
No error because name1
is an Object
array. In Java every class is an Object, even an array of Objects also an Object. Hence it accepted it as an Object. Though your name1 is an array of Objects, as a whole it is an Object itself first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With