给定两个集合A、B,验证集合的并、交、相对补和对称差运算。用java写
时间: 2024-01-25 20:02:49 浏览: 83
以下是在Java中验证集合的并、交、相对补和对称差运算的示例代码:
```java
import java.util.HashSet;
import java.util.Set;
public class SetOperations {
public static void main(String[] args) {
Set<Integer> setA = new HashSet<>();
Set<Integer> setB = new HashSet<>();
// 添加元素到集合A
setA.add(1);
setA.add(2);
setA.add(3);
setA.add(4);
// 添加元素到集合B
setB.add(3);
setB.add(4);
setB.add(5);
setB.add(6);
// 集合的并
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
System.out.println("集合的并:" + union);
// 集合的交
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
System.out.println("集合的交:" + intersection);
// 集合的相对补
Set<Integer> difference = new HashSet<>(setA);
difference.removeAll(setB);
System.out.println("集合的相对补:" + difference);
// 集合的对称差
Set<Integer> symmetricDifference = new HashSet<>(setA);
symmetricDifference.addAll(setB);
Set<Integer> tmp = new HashSet<>(setA);
tmp.retainAll(setB);
symmetricDifference.removeAll(tmp);
System.out.println("集合的对称差:" + symmetricDifference);
}
}
```
输出结果为:
```
集合的并:[1, 2, 3, 4, 5, 6]
集合的交:[3, 4]
集合的相对补:[1, 2]
集合的对称差:[1, 2, 5, 6]
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)