用集合A={1,2,3,4},B={1,3,5,9,11},选择合适的容器类,用Java编写程序求A与B的交/并/差
时间: 2024-05-01 16:19:05 浏览: 55
可以使用Java中的Set集合类来实现。
交集:
```java
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(1, 3, 5, 9, 11));
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
System.out.println("A与B的交集为:" + intersection);
```
并集:
```java
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(1, 3, 5, 9, 11));
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
System.out.println("A与B的并集为:" + union);
```
差集:
```java
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(1, 3, 5, 9, 11));
Set<Integer> diff = new HashSet<>(setA);
diff.removeAll(setB);
System.out.println("A与B的差集为:" + diff);
```
阅读全文