当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java AbstractCollection isEmpty()用法及代码示例


Java AbstractCollection 的 isEmpty() 方法用于检查和验证 Collection 是否为空。如果集合为空,则返回 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




相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 AbstractCollection isEmpty() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。