📌  相关文章
📜  Java中的 AbstractCollection isEmpty() 方法及示例

📅  最后修改于: 2022-05-13 01:54:53.782000             🧑  作者: Mango

Java中的 AbstractCollection isEmpty() 方法及示例

Java AbstractCollectionisEmpty()方法用于检查和验证 Collection 是否为空。如果集合为空,则返回 True,否则返回 False。

句法:

AbstractCollection.isEmpty()

参数:该方法不带任何参数。

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

下面的程序说明了 AbstractCollection.isEmpty() 方法的使用:

方案一:

// Java code to illustrate isEmpty() method
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Collection
        AbstractCollection
            abs = new TreeSet();
  
        // Use add() method to add
        // elements into the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("4");
        abs.add("Geeks");
        abs.add("TreeSet");
  
        // Displaying the Collection
        System.out.println("Collection: " + abs);
  
        // Check for the empty collection
        System.out.println("Is the collection empty? "
                           + abs.isEmpty());
  
        // Clearing the collection
        // using clear() method
        abs.clear();
  
        // Again Checking for the empty collection
        System.out.println("Is the collection empty? "
                           + abs.isEmpty());
    }
}
输出:
Collection: [4, Geeks, To, TreeSet, Welcome]
Is the collection empty? false
Is the collection empty? true

方案二:

// Java code to illustrate isEmpty() method
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Collection
        AbstractCollection
            abs = new ArrayList();
  
        // Use add() method to add
        // elements into the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("4");
        abs.add("Geeks");
        abs.add("ArrayList");
  
        // Displaying the Collection
        System.out.println("Collection: " + abs);
  
        // Check for the empty collection
        System.out.println("Is the collection empty? "
                           + abs.isEmpty());
  
        // Clearing the collection using clear() method
        abs.clear();
  
        // Again Checking for the empty collection
        System.out.println("Is the collection empty? "
                           + abs.isEmpty());
    }
}
输出:
Collection: [Welcome, To, Geeks, 4, Geeks, ArrayList]
Is the collection empty? false
Is the collection empty? true