72

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?

3

3 Answers 3

74

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
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

For example, List.of(...) will throw if the supplied value is null. This is dumb -- just putting it out there. It's perfectly legit to have a null value in a list!
List.of(...) will throw exception however Stream.of(null, "a").toList() works perfectly fine.
@JoshM. Weirdly enough, Collections.singletonList() does allow null, which means that the of method is even more "off". Anyway, if you need to create a list of one element that may be null then singletonList may help.
@MaartenBodewes that's ridiculous. Thanks for ruining my morning. :-D
35

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

Output :

2
null value
5

1 Comment

Thank you, I am guessing the .size() method also takes the null values into account.
3

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

1 Comment

This will never add anything to the list if the list is empty to begin with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.