views:

312

answers:

4
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

+3  A: 

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.

Uri
+1 - best answer out here :)
Webbisshh
+1  A: 

Because the arraylist still has 5 elements in it. They might be null, but they are still present in the list.

You can empty the ArrayList, by calling choice.clear();

Frederik Wordenskjold
+1  A: 

From the Javadocs for ArrayList:

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

ArrayLists can hold null elements, so the size is five. Keep in mind that if you simply declare a new ArrayList(5), it will have a initial capacity of 5, but the size() will be 0.

Justin Ardini
A: 

This is because the ArrayList is not null, it holds five objects (all are null), anyway an ArrayList never will have a null size, at least the size is 0 (zero), and if the ArrayList is not initialized (is null) and you try to access to the function size() it will threw a NullPointerException. I hope this information will be useful for you, and sorry for my bad english :(

gurbieta