获取Java中HashSet的大小

Get size of HashSet in Java

要获取HashSet的大小,请使用size()方法。 让我们创建一个HashSet并添加元素-

1
2
3
4
5
6
Set<Integer> hs = new HashSet<Integer>();
hs.add(15);
hs.add(71);
hs.add(82);
hs.add(89);
hs.add(91);

现在让我们使用size()并获取HashSet的大小-

1
hs.size()

以下是获取HashSet大小的示例-

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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());
   }
}

输出量

1
2
3
4
5
Elements = [82, 71, 89, 91, 15]
Size of Set: 5

Updated Elements = [71, 89, 15]
Size of Set now: 3