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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

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

đź‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay