Ask Question
2 June, 08:28

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
Answers (1)
  1. 2 June, 11:47
    0
    import java. util. Scanner;

    import java. util. ArrayList;

    public class Main

    {

    public static void main (String[] args) {

    Scanner input = new Scanner (System. in);

    ArrayList list1 = new ArrayList (5);

    ArrayList list2 = new ArrayList (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 union (ArrayList list1, ArrayList list2) {

    for (int l: list2) {

    list1. add (l);

    }

    return list1;

    }

    }

    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
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “1. Write a method that returns the union of two array lists of integers using the following header: public static ArrayList union ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers