user2995344
user2995344

Reputation: 268

How to use java empty HashSet in if-statement?

public static void main(String[] args) {
    Map<String, HashSet<String>> test = new HashMap<String, HashSet<String>>();

    test.put("1", new HashSet<String>());
    System.out.println(test);

    System.out.println(test.get("1"));

    if(test.get("1") == null){
        System.out.println("Hello world");
    }
}

The first println gets me {1=[]} The second one gets me []
I am trying to print out "Hello world" but the if statement isn't going through.
Is the empty HashSet, [] not equal to null?

How do I use the empty HashSet in this if statement?

Upvotes: 5

Views: 12852

Answers (4)

Adzz
Adzz

Reputation: 127

You should use the Set_Obj.isEmpty() method. This returns a boolean value checking if the set has any element in it (true).

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201497

The empty HashSet isn't a null. Add a test by using the HashSet.size()

if (test.get("1") == null || test.get("1").size() == 0) {

or use HashSet.isEmpty(),

if (test.get("1") == null || test.get("1").isEmpty()) {

Alternatively, you could comment out

// test.put("1", new HashSet<String>());
System.out.println(test);

Then test.get("1") is null.

Upvotes: 1

NPE
NPE

Reputation: 500733

Is the empty HashSet, [] not equal to null?

Correct, it is not. This is precisely the reason your code behaves the way it does.

To check for both null and empty set, use the following construct:

HashSet<String> set = test.get("1");
if (set == null || set.isEmpty()) {
  ...
}

Upvotes: 5

templatetypedef
templatetypedef

Reputation: 373032

There is a difference between null, which means "nothing at all," and an empty HashSet. An empty HashSet is an actual HashSet, but one that just coincidentally happens to not have any elements in it. This is similar to how null is not the same as the empty string "", which is a string that has no characters in it.

To check if the HashSet is empty, use the isEmpty method:

if(test.get("1").isEmpty()){
    System.out.println("Hello world");
}

Hope this helps!

Upvotes: 9

Related Questions