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=[]} second gets me []
I am trying to print "Hello world", but the if statement fails.
Is an empty HashSet, [] not null ?

How to use empty HashSet in this if statement?

+5
source share
3 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 accidentally matches the absence of any elements in it. This is similar to how null does not match the empty string "" , which is a string that has no characters.

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

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

Hope this helps!

+9
source

Is an empty HashSet , [] not null ?

That's right, it is not. It is for this reason that your code behaves the way it does.

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

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

An empty HashSet not null . Add a test using 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 can comment

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

Then test.get("1") null .

0
source

Source: https://habr.com/ru/post/1202612/


All Articles