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


Java AbstractCollection size()用法及代碼示例


Java AbstractCollection 的 size() 方法用於獲取 Collection 的大小或 Collection.Syntax 中存在的元素數量:

AbstractCollection.size()

參數:該方法不帶任何參數。
返回值:該方法返回集合中存在的元素的大小或數量。以下程序說明了 AbstractCollection.size() 方法的使用:程序 1:

Java


// Java code to illustrate size()
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);
        // Displaying the size of the collection
        System.out.println("The size of the Collection is:"
                           + abs.size());
    }
}
輸出:
Collection:[4, Geeks, To, TreeSet, Welcome]
The size of the Collection is:5

程序2:

Java


// Java code to illustrate size()
import java.util.*;
import java.util.AbstractCollection;
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
        // Creating an empty Collection
        AbstractCollection<String>
            abs = new LinkedList<String>();
        // Using add() method to add
        // elements in the Collection
        abs.add("Geeks");
        abs.add("for");
        abs.add("Geeks");
        abs.add("10");
        abs.add("20");
        // Displaying the Collection
        System.out.println("Collection:" + abs);
        // Displaying the size of the Collection
        System.out.println("The size of the Collection is:"
                           + abs.size());
    }
}
輸出:
Collection:[Geeks, for, Geeks, 10, 20]
The size of the Collection is:5




相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 AbstractCollection size() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。