In java write a method that returns the union of two array lists of integers usi
ID: 3805239 • Letter: I
Question
In java write a method that returns the union of two array lists of integers using the following header:
public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2)
For example, the union of two array lists {2, 3, 1, 5} and {3, 4, 6} is {2, 3, 1, 5, 3, 4, 6}. Write a test program that prompts the user to enter two lists, each with five integers, and displays their union. The numbers are separated by exactly one space in the output. Here is a sample run:
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
Explanation / Answer
ArrayListUnion.java
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListUnion {
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Enter five integers for list1: ");
for(int i=0; i<5; i++){
list1.add(scan.nextInt());
}
System.out.print("Enter five integers for list2: ");
for(int i=0; i<5; i++){
list2.add(scan.nextInt());
}
ArrayList<Integer> list3 = union(list1, list2);
System.out.print("The combined list is ");
for(int i=0; i<list3.size(); i++){
System.out.print(list3.get(i)+" ");
}
System.out.println();
}
public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2) {
ArrayList<Integer> list3 = new ArrayList<Integer>();
for(int i=0; i<list1.size(); i++){
list3.add(list1.get(i));
}
for(int i=0; i<list2.size(); i++){
list3.add(list2.get(i));
}
return list3;
}
}
Output:
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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.