Search code examples
javacollectionsimmutability

Why does ImmutableCollection.contains(null) fail?


Question ahead: why does in Java the call coll.contains(null) fail for ImmutableCollections?

I know, that immutable collections cannot contain null-elements, and I do not want to discuss whether that's good or bad.

But when I write a Function, that takes a (general, not explicit immutable) Collection, it fails upon checking for nulls. Why does the implementation not return false (which is actually the 'correct' answer)?

And how can I properly check for nulls in a Collection in general?

Edit: with some discussions (thanks to the commenters!) I realized, that I mixed up two things: ImmutableCollection from the guava library, and the List returned by java.util.List.of, being some class from ImmutableCollections. However, both classes throw an NPE on .contains(null).

My problem was with the List.of result, but technically the same would happen with guaves implementation. [edit: It does not]


Solution

  • I am distressed by this discussion!

    Collections that do this have been a pet peeve of mine since before I wrote the first collections that eventually became Guava. If you find any Guava collection that throws NPE just because you asked it a perfectly innocent question like .contains(null), please file a bug! We hate that crap.

    EDIT: I was so distressed that I had to go back to look at my 2007 changelist that first created ImmutableSet and saw literally this:

      @Override public boolean contains(@Nullable Object target) {
        if (target == null) {
          return false;
        }
    

    ahhhhh.