Adding null values to 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?


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
        }
 }