已知集合A与集合B,且第个集合内数据是唯一的。求A,B集合合并成新的集合C,要求C集合内的数据也是唯一的。并指出C集合的个数。 java 编写程序
时间: 2024-05-16 18:14:20 浏览: 80
你可以使用 Java 中的 Set 集合来实现去重的功能,Set 集合中的元素是不允许重复的,将 A、B 集合的元素全部添加到一个新的 Set 集合中,就可以得到合并后去重的集合 C 了。
以下是示例代码:
```java
import java.util.HashSet;
import java.util.Set;
public class MergeSetDemo {
public static void main(String[] args) {
Set<Integer> setA = new HashSet<>();
Set<Integer> setB = new HashSet<>();
// 初始化集合 A 和集合 B
setA.add(1);
setA.add(2);
setA.add(3);
setB.add(3);
setB.add(4);
setB.add(5);
// 合并集合 A 和集合 B
Set<Integer> setC = new HashSet<>(setA);
setC.addAll(setB);
// 输出集合 C 中的元素
for (Integer i : setC) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("集合 C 中的元素个数为:" + setC.size());
}
}
```
输出结果为:
```
1 2 3 4 5
集合 C 中的元素个数为:5
```
阅读全文