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

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

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

语法:

AbstractCollection.isEmpty()

参数: 该方法不需要任何参数。

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

下面的程序示例展示了AbstractCollection.isEmpty()方法的使用:

程序1:

// 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<String>
            abs = new TreeSet<String>();
  
        // 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

程序2:

// 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<String>
            abs = new ArrayList<String>();
  
        // 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程