Write a method that returns the union of two array lists of integers using the f
ID: 642068 • Letter: W
Question
Write a method that returns the union of two array lists of integers using the following header: public static ArrayList union( ArrayList list1, ArrayList 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 the two lists, each with five numbers and display the union. The numbers are to separated by exactly ONE space in the output. Sample run: Enter list1 : 3 5 45 4 3 Enter list2: 33 51 5 4 13 Union is 3 4 45 4 3 33 51 5 4 13
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class UnionList
{
public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2 )
{
ArrayList<Integer> union_ = new ArrayList<Integer>();
for(int i=0;i<list1.size();i++)
{
union_.add(list1.get(i));
}
for(int i=0;i<list2.size();i++)
{
union_.add(list2.get(i));
}
return union_;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
ArrayList<Integer> array1 = new ArrayList<>();
ArrayList<Integer> array2 = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Input the numbers with a space for array 1 : ");
String line = input.nextLine();
String[] s2 = line.split(" ");
for(String results : s2) {
array1.add(Integer.parseInt(results));
}
System.out.println("Input the numbers with a space for array 2 : ");
line = input.nextLine();
s2 = line.split(" ");
for(String results : s2) {
array2.add(Integer.parseInt(results));
}
ArrayList<Integer> union_ = union(array1,array2);
int value;
for (int i = 0; i < union_.size(); i++) {
value = union_.get(i);
System.out.println("Element: " + value);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.