[英]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");
}
}
第一個println讓我{1=[]}
第二個得到我[]
我正在嘗試打印出“Hello world”,但if語句沒有通過。
是空的HashSet, []
不等於null
?
如何在此if語句中使用空HashSet?
null
之間存在差異,這意味着“什么都沒有”,以及空HashSet
。 一個空的HashSet
是一個真正的HashSet
,但恰好碰巧沒有任何元素。 這類似於null
與空字符串""
,空字符串""
是一個沒有字符的字符串。
要檢查HashSet
是否為空,請使用isEmpty
方法:
if(test.get("1").isEmpty()){
System.out.println("Hello world");
}
希望這可以幫助!
是空的
HashSet
,[]
不等於null
?
正確,事實並非如此。 這正是您的代碼行為方式的原因。
要檢查null
和empty set,請使用以下構造:
HashSet<String> set = test.get("1");
if (set == null || set.isEmpty()) {
...
}
空HashSet
不是null
。 使用HashSet.size()
添加測試
if (test.get("1") == null || test.get("1").size() == 0) {
或者使用HashSet.isEmpty()
,
if (test.get("1") == null || test.get("1").isEmpty()) {
或者,您可以注釋掉
// test.put("1", new HashSet<String>());
System.out.println(test);
然后test.get("1")
為null 。
您應該使用Set_Obj.isEmpty()方法。 這將返回一個布爾值,檢查該集合中是否包含任何元素(true)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.