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.
Check for Not Null ElementsaddIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.
Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.
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.
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With