Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set arrayList size as null?

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

like image 779
Jessy Avatar asked Apr 01 '10 01:04

Jessy


People also ask

Can you set an ArrayList 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.

Is an ArrayList of size 0 null?

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.

How do you set an ArrayList to a specific size?

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.

How do you make an ArrayList empty?

The clear() method of ArrayList in Java is used to remove all the elements from a list.


2 Answers

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();

like image 158
Frederik Wordenskjold Avatar answered Oct 05 '22 22:10

Frederik Wordenskjold


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.

like image 33
Uri Avatar answered Oct 05 '22 22:10

Uri