13.7k views
0 votes
Write a method that returns the union of two arrays lists of integers using the following header:

Public static ArrayList union(Array list, ArrayList list2)
For example, the addition 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 number are separated by exactly one space. 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

User Atan
by
6.9k points

1 Answer

3 votes

Answer:

import java.util.*;

public class Main

{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

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

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

System.out.println("Enter five integers for list1: ");

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

int x = input.nextInt();

l1.add(x);

}

System.out.println("Enter five integers for list2: ");

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

int x = input.nextInt();

l2.add(x);

}

System.out.println(union(l1, l2));

}

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

for (int i:list2)

list.add(i);

return list;

}

}

Step-by-step explanation:

Create a method called union takes two lists, list and list2

Inside the method:

Initialize a for loop iterates through the list2

Add all the elements in list2 to list

Return the list

Inside the main:

Declare the lists

Ask the user for the numbers and put them in the lists

Call the union method to combine the lists and print the combined list

User Sheerun
by
7.4k points