要获取HashSet的大小,请使用size()
方法。让我们创建一个HashSet并添加元素-
Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91);
现在让我们使用size()
并获取HashSet的大小-
hs.size()
以下是获取HashSet大小的示例-
import java.util.*; public class Demo { public static void main(String args[]) { Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91); System.out.println("Elements = "+hs); System.out.println("Size of Set: "+hs.size()); hs.remove(82); hs.remove(91); System.out.println("\nUpdated Elements = "+hs); System.out.println("Size of Set now: "+hs.size()); } }
输出结果
Elements = [82, 71, 89, 91, 15] Size of Set: 5 Updated Elements = [71, 89, 15] Size of Set now: 3