DEV Community

smolthing
smolthing

Posted on

Set.of().contains(null)

raises a NullPointerException.

import java.util.*;

public class NullPointer {
    public static void main(String[] args) {
        Set<Integer> hashSetContainsNull = new HashSet<>();
        hashSetContainsNull.add(null);
        hashSetContainsNull.contains(null);

        // hashSetAllowsNull [null, 1]
        System.out.println("hashSetContainsNull " + hashSetContainsNull);

        Set<Integer> setOfNotContainsNull = Set.of();
        // Even `contains` will throw NullPointerException
        setOf.contains(null);

        // Exception in thread "main" java.lang.NullPointerException
        // at java.base/java.util.Objects.requireNonNull(Objects.java:208)
        // at java.base/java.util.ImmutableCollections$SetN.contains(ImmutableCollections.java:937)
        System.out.println("setOf " + setOfNotContainsNull);
    }
}

Enter fullscreen mode Exit fullscreen mode

I encountered an unexpected NullPointerException while reusing an empty set validation check in multiple handlers. The issue stemmed from using .contains with different types of empty sets.

One handler gave back Set.of(), which doesn't accept null elements; trying .contains with null would cause an issue. Meanwhile, the other handler returned a HashSet, where null elements can be stored.

I solve the NullPointerException by using Collections.emptySet() instead of Set.of(). Tada.

Top comments (0)