DEV Community

smolthing
smolthing

Posted on

2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more