According to the documentation, List.contains
can throw NullPointerException
in this scenario:
"if the specified element is null and this list does not support null elements (optional)."
I was just trying to think of a List implementation that doesn't allow nulls though, and I'm not aware of any. For example, I can have ArrayList<Double>
, but it allows nulls.
List<Double> list = new ArrayList<Double>();
if (list.contains(null)) { // this won't throw NPE
}
So is the documentation here referring to custom implementations of this interface, or are there some native JAVA collection classes that extend List
that don't allow null elements? I realize the exception is optional, I was just trying to think of a real world case where this could occur.
Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.
Solution. Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.
Class ArrayList<E> Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.
addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.
Not all implementations of List<...> allow for elements to be null.
An example is RoleList::add(role)
that throws an exception when adding a Null value.
This documentation prepares you for such an encounter, encouraging you to check the documentation of whatever list you're working with to see if it's a concern, or to err on the side of caution if you are unable to check it. Tracking down NPE's is not fun. Knowing documentation (provided good documentation exists) can save a lot of headaches.
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