简体   繁体   中英

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?

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!

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()) {
  ...
}

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM