(合并两个列表)使用下面的方法头编写一个方法,返回两个数组列表的并集。 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-07 12:05:19 浏览: 127
C语言 并集
4星 · 用户满意度95%
以下是实现上述功能的 Java 代码:
```
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two lists
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());
}
// Find the union of the two lists
ArrayList<Integer> unionList = union(list1, list2);
// Display the combined list
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> unionList = new ArrayList<>();
// Add elements of list1 to the union list
for (int i = 0; i < list1.size(); i++) {
unionList.add(list1.get(i));
}
// Add elements of list2 to the union list if they are not already in it
for (int i = 0; i < list2.size(); i++) {
int num = list2.get(i);
if (!unionList.contains(num)) {
unionList.add(num);
}
}
return unionList;
}
}
```
运行示例:
```
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
```
阅读全文