Java HashSet ``isEmpty()`` 方法详解:语法、示例与判断空集合


发布日期 : 2023-10-16 04:54:17 UTC

访问量: 10 次浏览

Java HashSet isEmpty()方法

Java java.util.HashSet.isEmpty()方法用于检查一个HashSet是否为空。如果HashSet是空的,它就返回True,否则就返回False

语法

Hash_Set.isEmpty()

参数:该方法不接受任何参数

返回值:如果集合为空,该函数返回True,否则返回False

下面的程序说明了 Java util.HashSet.isEmpty()方法。

// Java code to illustrate contains()
import java.io.*;
import java.util.HashSet;
  
public class HashSetDemo {
    public static void main(String args[])
    {
        // Creating an empty HashSet
        HashSet<String> set = new HashSet<String>();
  
        // Use add() method to add elements into the Set
        set.add("Welcome");
        set.add("To");
        set.add("Geeks");
        set.add("4");
        set.add("Geeks");
  
        // Displaying the HashSet
        System.out.println("HashSet: " + set);
  
        // Check for the empty set
        System.out.println("Is the set empty: " + set.isEmpty());
  
        // Clearing the set using clear() method
        set.clear();
  
        // Again Checking for the empty set
        System.out.println("Is the set empty: " + set.isEmpty());
    }
}

输出:

HashSet: [4, Geeks, Welcome, To]
Is the set empty: false
Is the set empty: true