给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集,输出从小到大。用Java实现
时间: 2023-11-28 12:48:24 浏览: 100
可以使用Java中的集合类来实现,具体实现代码如下:
```java
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
// 定义集合A和B
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> setB = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
// 求交集
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
System.out.println("Intersection: " + intersection);
// 求并集
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
System.out.println("Union: " + union);
// 求B在A中的余集
Set<Integer> difference = new HashSet<>(setA);
difference.removeAll(setB);
System.out.println("B's complement in A: " + difference);
}
}
```
输出结果为:
```
Intersection: [3, 4, 5]
Union: [1, 2, 3, 4, 5, 6, 7]
B's complement in A: [1, 2]
```
阅读全文