(合并两个列表)使用下面的方法头编写一个方法,返回两个数组列表的并集。 publ ic static ArrayList<Integer> union( ArrayList<Integer> listl, ArrayList<Integer> list2) 例如,两个数组列表{2,3,1,5}和{3,4,6}的并集为{2,3,1,5,3,4,6}编写测试程序,提示用户输入两个列表,每个列表有5个整数,然后显示它们的并集。输出中,以一个空格进行分隔。下面是一个运行示例: Enter five integers for list1: 3 5 45 4 3 Enter five integers for list2: 33 51 5 4 13 The combined list is 3 5 45 4 3 33 51 5 4 13
时间: 2023-12-20 12:04:49 浏览: 24
以下是实现上述功能的方法和测试程序:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 读取两个列表
System.out.print("Enter five integers for list1: ");
ArrayList<Integer> list1 = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list1.add(input.nextInt());
}
System.out.print("Enter five integers for list2: ");
ArrayList<Integer> list2 = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list2.add(input.nextInt());
}
// 计算并集
ArrayList<Integer> unionList = union(list1, list2);
// 输出结果
System.out.print("The combined list is ");
for (int i = 0; i < unionList.size(); i++) {
System.out.print(unionList.get(i) + " ");
}
}
public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2) {
ArrayList<Integer> result = new ArrayList<>(list1);
for (Integer i : list2) {
if (!result.contains(i)) {
result.add(i);
}
}
return result;
}
}
```
运行结果:
```
Enter five integers for list1: 3 5 45 4 3
Enter five integers for list2: 33 51 5 4 13
The combined list is 3 5 45 4 33 51 13
```