Is there a standard Java List implementation that doesn't allow adding null to it?

Viewed 63004

Say I have a List and I know that I never want to add null to it. If I am adding null to it, it means I'm making a mistake. So every time I would otherwise call list.add(item) I would instead call if (item == null) throw SomeException(); else list.add(item);. Is there an existing List class (maybe in Apache Commons or something) that does this for me?

Similar question: Helper to remove null references in a Java List? but I don't want to remove all the nulls, I want to make sure they never get added in the first place.

9 Answers

If it's ok to create a list and not mutate existing one, List.of added in Java 9 throws NPE when element added is null

This might help you if you want to add an item to the list and silently ignore if the value is null:

You need Apache Commons Collections 4:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

Then, you need to import:

import org.apache.commons.collections4.CollectionUtils;

Now, use it like:

List<String> someList = new ArrayList<>();
String nullItem = null;
String normalItem = "Text";

CollectionUtils.addIgnoreNull(someList, nullItem);
CollectionUtils.addIgnoreNull(someList, normalItem);

Eventually, someList will just have 1 item. null will be ignored.

Related