Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
user2995344 Avatar asked Sep 15 '14 19:09

user2995344


People also ask

How check if HashSet is empty?

HashSet. isEmpty() method is used to check if a HashSet is empty or not. It returns True if the HashSet is empty otherwise it returns False. Return Value: The function returns True if the set is empty else returns False.

How do you make a HashSet empty?

clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet. Return Value: The function does not returns any value.

Is an empty HashSet null?

Is the empty HashSet , [] not equal to null ? Correct, it is not. This is precisely the reason your code behaves the way it does.

How do you check if a HashSet contains an element?

The contains() method of Java HashSet class is used to check if this HashSet contains the specified element or not. It returns true if element is found otherwise, returns false.


1 Answers

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!

like image 112
templatetypedef Avatar answered Oct 27 '22 00:10

templatetypedef