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?
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.
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 the empty HashSet , [] not equal to null ? Correct, it is not. This is precisely the reason your code behaves the way it does.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With