Java Set isEmpty()方法及示例

Java Set isEmpty()方法及示例

java.util.Set.isEmpty()方法用于检查一个Set是否为空。如果该集合是空的,它将返回True,否则将返回False。

语法

boolean isEmpty()

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

返回值: 如果集合为空,该方法返回True,否则返回False。

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

// Java code to illustrate isEmpty()
import java.io.*;
import java.util.*;
  
public class SetDemo {
    public static void main(String args[])
    {
        // Creating an empty Set
        Set<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 Set
        System.out.println("Set: " + 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());
    }
}

输出。

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

参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#isEmpty()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程