set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;

public static void main(String[] args) {
Set<Integer> result = new HashSet<Integer>();
Set<Integer> set1 = new HashSet<Integer>(){{
add(1);
add(3);
add(5);
}};

Set<Integer> set2 = new HashSet<Integer>(){{
add(1);
add(2);
add(3);
}};

result.clear();
result.addAll(set1);
result.retainAll(set2);
System.out.println("交集:"+result);

result.clear();
result.addAll(set1);
result.removeAll(set2);
System.out.println("差集:"+result);

result.clear();
result.addAll(set1);
result.addAll(set2);
System.out.println("并集:"+result);