在 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

更新於: 30-7-2019

1K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.