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


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


Java 集合接口的 size() 方法返回此集合中包含的元素的總數。

用法

public int size()

參數

NA

返回值

size() 方法返回此集合中存在的元素的總數。

例子1

import java.util.Collection;
import java.util.HashSet;
public interface JavaCollectionSizeExample1 {
    public static void main(String[] args) {
        Collection<Integer> collection = new HashSet<>();
        //add integer values in this collection
        collection.add(34);
        collection.add(12);
        collection.add(45);
        System.out.print("The elements in Collection:");
        System.out.println(collection);
        //returns the size of the collection
        System.out.println("Size of the collection "+collection.size());
    }
}

輸出:

The elements in Collection:[34, 12, 45]
Size of the collection 3

例子2

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaCollectionSizeExample2 {
    public static void main(String[] args) {
        Collection<Character> collection = new ConcurrentLinkedQueue<Character>();
        char i;
        for(i='a';i<='z';++i){
            collection.add(i);
        }
        //returns the total size of the collection
        System.out.println("Total alphabets:"+collection.size());
        System.out.println("collection:"+collection);
        List<Character> list = new ArrayList<Character>();
        list.add('a');
        list.add('e');
        list.add('i');
        list.add('o');
        list.add('u');
        collection.retainAll(list);
        // returns the size of the collection
        System.out.println("Number of vowels:"+collection.size());
        System.out.println("Vowels:"+collection);
      }
}

輸出:

Total alphabets:26
collection:[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
Number of vowels:5
Vowels:[a, e, i, o, u]

例子3

import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaCollectionSizeExample3 {
    public static void main(String[] args) {
        Collection<Integer> collection = new ConcurrentLinkedQueue<Integer>();
        //returns true if the queue is empty
        if(collection.size()==0){
            System.out.println("The queue is empty.");
        }
        else{
            System.out.println("Total elements are:"+collection.size());
        }
    }
}

輸出:

The queue is empty.




相關用法


注:本文由純淨天空篩選整理自 Java Collection size() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。