检查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[]) {
      //创建一个哈希集
      HashSet hs = new 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");
      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();
      //空集
      System.out.println("Is the set empty? = "+hs.isEmpty());
   }
}

输出结果

Is the set empty? = true