在Java中使用Example设置size()方法
java.util.Set.size()方法用于获取Set的大小或Set中存在的元素数量。
语法:
int size()
参数: 此方法不需要任何参数。
返回值: 该方法返回Set中存在的大小或元素数量。
以下程序说明java.util.Set.size()方法:
// Java code to illustrate Set.size() method
import java.util.*;
public class SetDemo {
public static void main(String args[])
{
// Creating an empty Set
Set<String> set = new HashSet<String>();
// Use add() method to add elements into the Set
set.add("Welcome");
set.add("To");
set.add("Geeks");
set.add("4");
set.add("Geeks");
// Displaying the Set
System.out.println("Set: " + set);
// Displaying the size of the Set
System.out.println("The size of the set is: " + set.size());
}
}
Set: [4, Geeks, Welcome, To]
The size of the set is: 4
参考文献: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
极客教程