獲取 Java 中 HashSet 的大小
若要獲取 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("
Updated 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
廣告