Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there native JAVA collection classes that extend List that don't allow null elements?

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.

like image 614
dcp Avatar asked Jun 29 '10 13:06

dcp


People also ask

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 list allow null values in Java?

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.

Does ArrayList support null?

Class ArrayList<E> Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

How do you add to a non null list in Java?

addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.


1 Answers

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.

like image 84
corsiKa Avatar answered Sep 28 '22 02:09

corsiKa