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.
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.