String a []= {null,null,null,null,null};
//add array to arraylist
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a));
System.out.println(choice.size());
Why the size of the arrayList choice
is 5 when all the elements have been set to null
An ArrayList element can be an object reference or the value null . When a cell contains null , the cell is not considered to be empty.
An Array list can't be NULL & 0 at same time. But it doesn't meant that a not null array list always have size > 0. Array list which is Not Null, can also have size 0. Always ensure that ArrayList is not null before calling arrayList.
To create an ArrayList of specific size, you can pass the size as argument to ArrayList constructor while creating the new ArrayList. Following the syntax to create an ArrayList with specific size. myList = new ArrayList<T>(N); where N is the capacity with which ArrayList is created.
The clear() method of ArrayList in Java is used to remove all the elements from a list.
Because the ArrayList still contains 5 Objects. They are null, but they are objects, thus present in the list!
You can empty the ArrayList, by calling choice.clear();
I think that what is confusing you is that you are thinking of the ArrayList as an ArrayList of objects, not as an ArrayList of references to objects.
An ArrayList of Object represents an index-accessible list of references to objects.
It is valid for such a reference to not refer to a real object but instead be "null".
Hence, you have five reference "slots", each with a value of null.
This is not the same as a series of four nulls, or zero nulls.
Look at your initial and primitive array of strings - its length is five, not zero.
Or even simpler, when you have a class with a field of type Object, it still takes space, regardless of whether it is actually referring to something or is null. Otherwise, you wouldn't be able to instantiate the class and not need to reallocate it when you actually assigned something to the field.
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