在 Java 中檢查一個 HashSet 是否為空
若要檢查一個 HashSet 是否為空,請使用 isEmpty() 方法。
建立一個 HashSet −
HashSet hs = new HashSet();
向 HashSet 中新增元素 −
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");現在,檢查 HashSet 是否為空。由於我們在上面添加了元素,因此它不會為空 −
hs.isEmpty();
以下是一個檢查 HashSet 是否為空的示例 −
示例
import java.util.*;
public class Demo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");
System.out.println("Elements: "+hs);
System.out.println("Is the set empty? = "+hs.isEmpty());
}
}輸出
Elements: [A, B, C, D, E, F, K, M, N] Is the set empty? = false
讓我們看另一個示例 −
示例
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet hs = new HashSet();
// empty set
System.out.println("Is the set empty? = "+hs.isEmpty());
}
}輸出
Is the set empty? = true
廣告
資料結構
聯網
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP