129k views
3 votes
1.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 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:

1 Answer

5 votes

Answer:

import java.util.Scanner;

import java.util.ArrayList;

public class Main

{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

ArrayList<Integer> list1 = new ArrayList<Integer>(5);

ArrayList<Integer> list2 = new ArrayList<Integer>(5);

System.out.print("Enter the numbers for the first list: ");

for (int i=0; i<5; i++)

list1.add(input.nextInt());

System.out.print("Enter the numbers for the second list: ");

for (int i=0; i<5; i++)

list2.add(input.nextInt());

union(list1, list2);

System.out.print("The unioned list is: ");

for (int x: list1)

System.out.print(x + " ");

}

public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2) {

for (int l: list2) {

list1.add(l);

}

return list1;

}

}

Step-by-step explanation:

Create a method called union takes two ArrayLists, list1 and list2

Inside the method, create a for loop to add the numbers in list2 to list1

Return the list1

Inside the main:

Declare the two lists

Ask the user for the numbers to fill the lists

Call the union method with the created lists, it will add the elements in list2 to list 1

Print the list that is unioned

User Roxie
by
4.9k points