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 spliterator()用法及代码示例
- Java Collection retainAll()用法及代码示例
- Java Collection toArray()用法及代码示例
- Java Collection addAll()用法及代码示例
- Java Collection add()用法及代码示例
- Java Collection removeAll()用法及代码示例
- Java Collection remove()用法及代码示例
- Java Collection equals()用法及代码示例
- Java Collection hashCode()用法及代码示例
- Java Collection contains()用法及代码示例
- Java Collection containsAll()用法及代码示例
- Java Collection removeIf()用法及代码示例
- Java Collection clear()用法及代码示例
- Java Collection isEmpty()用法及代码示例
- Java Collection iterator()用法及代码示例
- Java Collections synchronizedSortedSet()用法及代码示例
- Java Collections checkedQueue()用法及代码示例
- Java Collections unmodifiableNavigableSet()用法及代码示例
- Java Collections checkedSet()用法及代码示例
- Java Collections copy()用法及代码示例
注:本文由纯净天空筛选整理自 Java Collection size() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。