How to set array 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 is the size of arrayList choice equal to 5 if all elements are set to null

+4
source share
4 answers

Because arraylist still has 5 elements. They may be empty, but they are still on the list.

You can remove ArrayList by calling choice.clear();

+2
source

I think you are confused about what you think of ArrayList as ArrayList objects, not ArrayList object references.

ArrayList of Object represents a list of object references available for the index.

Indeed, for such a reference, do not refer to the real object, but instead to "null".

Therefore, you have five reference slots, each with a null value.

This is not the same as a series of four zeros or zero zeros.

Look at your initial and primitive array of strings - its length is five, not zero.

Or even easier, when you have a class with a field of type Object, it still takes a space, regardless of whether it refers to something or not. Otherwise, you will not be able to instantiate the class and not redistribute it when you really assigned something to the field.

+4
source

From Javadocs for ArrayList:

Implementable implementation of the List interface array. Implements all optional operations with lists and permissions all elements, including null.

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

+1
source

This is due to the fact that the ArrayList is not null, it contains five objects (all are null), in any case, the ArrayList will never have a zero size, at least the size is 0 (zero), and if the ArrayList is not initialized (is null ), and you are trying to access the size of the function (), it will throw a NullPointerException. I hope this information is useful to you, and sorry for my poor English :(

+1
source

Source: https://habr.com/ru/post/1305716/


All Articles