Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding null values to arraylist

Tags:

java

arraylist

Can I add null values to an ArrayList even if it has a generic type parameter?

Eg.

ArrayList<Item> itemList = new ArrayList<Item>(); itemList.add(null); 

If so, will

itemsList.size(); 

return 1 or 0?

If I can add null values to an ArrayList, can I loop through only the indexes that contain items like this?

for(Item i : itemList) {    //code here } 

Or would the for each loop also loop through the null values in the list?

like image 283
Nick Bishop Avatar asked Nov 24 '14 14:11

Nick Bishop


People also ask

Can you add null value to ArrayList?

Yes, you can always use null instead of an object.

What happens if you add null to ArrayList?

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. The picture shows empty cells with an "X" and cells that contain a null with null . The cells that contain null are not empty, and contribute to the size of the list.

Can we put null value in list?

Solution. Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.

How do you add null values to an array in Java?

int[] a = new int[5]; a[0] = 1; a[2] = 'a'; a[3] = null; //Compiler complains here for (int i : a) System. out. println(i); I am assuming because its an int array and the literal value allowed is 0 and not NULL .


1 Answers

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

Also nulls would be factored in in the for loop, but you could use

for (Item i : itemList) {     if (i != null) {        //code here     } } 
like image 116
deme72 Avatar answered Sep 19 '22 10:09

deme72