Adding null values to arraylist

arraylist, java

Solution

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

It would be 1.

Also `null`s would be factored in in the for loop, but you could use

for (Item i : itemList) {
    if (i != null) {
       //code here
    }
}

Problem

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?

Original source

Related problems