Ask Question
6 November, 02:25

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:

+3
Answers (1)
  1. 6 November, 03:51
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers