编制一个能演示执行集合的并、交和差运算的程序java
时间: 2024-05-04 21:17:05 浏览: 16
下面是一个简单的 Java 程序,用于演示执行集合的并、交和差运算。
```java
import java.util.HashSet;
import java.util.Set;
public class SetOperations {
public static void main(String[] args) {
Set<Integer> setA = new HashSet<Integer>();
Set<Integer> setB = new HashSet<Integer>();
setA.add(1);
setA.add(2);
setA.add(3);
setB.add(2);
setB.add(3);
setB.add(4);
// 求并集
Set<Integer> union = new HashSet<Integer>(setA);
union.addAll(setB);
System.out.println("并集: " + union);
// 求交集
Set<Integer> intersection = new HashSet<Integer>(setA);
intersection.retainAll(setB);
System.out.println("交集: " + intersection);
// 求差集
Set<Integer> difference = new HashSet<Integer>(setA);
difference.removeAll(setB);
System.out.println("差集(A-B): " + difference);
}
}
```
代码中,我们使用了 HashSet 类来表示集合,并使用了 add() 方法向集合中添加元素。然后,我们使用了 retainAll()、removeAll() 和 addAll() 等方法来执行集合的交、差和并运算。最后,我们使用了 System.out.println() 方法来输出结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)