Adding null values to arraylist

Tags: ,

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


ArrayList<Item> itemList = new ArrayList<Item>();

If so, will


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?


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

Source: stackoverflow