當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。