Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 403
Tyler Avatar asked Jun 22 '11 00:06

Tyler


People also ask

How do I stop adding null to list?

Check for Not Null ElementsaddIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.

Which Java collection does not allow null?

Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.

Does ArrayList allow null values in Java?

In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number.


2 Answers

Watch out -- several answers here are claiming to solve your problem by wrapping a list and checking in add and addAll, but they're forgetting you can also add to a List via its listIterator. It's challenging to get a constrained list right, which is why Guava has Constraints.constrainedList to do it for you.

But before looking at that, first consider whether you only need an immutable list, in which case Guava's ImmutableList will do that null checking for you anyway. And in the off chance that you can use one of the JDK's Queue implementations instead, that'll do it too.

(Good list of null-hostile collections: https://github.com/google/guava/wiki/LivingWithNullHostileCollections)

like image 154
Kevin Bourrillion Avatar answered Sep 28 '22 02:09

Kevin Bourrillion


Use Apache Commons Collection:

ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate()); 

Adding null to this list throws IllegalArgumentException. Furthermore you can back it by any List implementation you like and if necessary you can add more Predicates to be checked.

Same exists for Collections in general.

Use Google Guava:

Constraints.constrainedList(new ArrayList(), Constraints.notNull()) 

Adding null to this list throws NullPointerException.

like image 31
Fabian Barney Avatar answered Sep 28 '22 02:09

Fabian Barney