Are there native JAVA collection classes that extend a list that does not allow null elements?

According to the documentation , List.contains may throw a NullPointerException in this scenario:

"if the specified item is NULL this list does not support null items (optional).

I was just trying to recall a List implementation that doesn't allow null, but I don't know about it. For example, I can have an ArrayList<Double> , but it allows null.

  List<Double> list = new ArrayList<Double>(); if (list.contains(null)) { // this won't throw NPE } 

So, is there any documentation related to user implementations of this interface, or are there some native JAVA collection classes that extend List that don't allow null elements? I understand that an exception is optional, I was just trying to think about the real world where this could happen.

+7
java nullpointerexception
source share
5 answers

Not all List <...> implementations allow elements to be null.

An example is RoleList::add(role) , which throws an exception when adding a Null value.

This documentation prepares you for such a meeting, prompting you to check the documentation for any list you are working with to find out if this is a problem, or to make a mistake with caution if you cannot check it. NPE tracking is not fun. Knowing the documentation (with good documentation) can save you a lot of headaches.

+5
source share

This applies to user implementations, until the day when one of the Java list implementations prohibits null, and then it will also refer to it.

+5
source share

Guava ImmutableList forbids null, but returns false on contains(null) .

+2
source share

--- Post Edited in response to comments ---

Basically, the reason it should remind you to catch NullPointerExcepton is because the List interface designers assumed lists that could report any null access as an error.

--- The original message follows ---

Those provided by the standard Java libraries support null, but there are no restrictions on creating a class that implements java.util.List that does not support null s.

If the list does not support null , then checking for null equivalent to an error, so an exception may make sense depending on who implemented the List . This is why the interface should mention a checked exception; because if it is not, then you cannot throw a NullPointerException from a subclass if you want no one to touch the list with null .

+1
source share

A CheckedList will be an example of a list in a standard API that does not support zeros.

+1
source share

All Articles