127k views
1 vote
The arrays list1 and list2 are identical if they have the same contents. Write a method that returns true if list1 and list2 are identical, using the following header: public static boolean equals (int[] list1, int[] list2) Write a test program that prompts the user to enter two lists of integers and displays whether the two are identical. Here are some sample runs. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list.

1 Answer

4 votes

Answer:

See Explaination

Step-by-step explanation:

import java.util.Arrays;

/**

*

* atauthor xxxx //replace at with the at symbol

*/

public class Test {

public static void main(String[] args) {

java.util.Scanner input = new java.util.Scanner(System.in);

// Enter values for list1

System.out.print("Enter list1: ");

int size1 = input.nextInt();

int[] list1 = new int[size1];

for (int i = 0; i < list1.length; i++)

list1[i] = input.nextInt();

// Enter values for list2

System.out.print("Enter list2: ");

int size2 = input.nextInt();

int[] list2 = new int[size2];

for (int i = 0; i < list2.length; i++)

list2[i] = input.nextInt();

if (equal(list1, list2)) {

System.out.println("Two lists are identical");

}

else {

System.out.println("Two lists are not identical");

}

}

public static boolean equal(int[] list1, int[] list2) {

if(list1.length == list2.length)

Arrays.sort(list1);

return true;

else

Arrays.sort(list2);

return false;

// Hint: (1) first check if the two have the same size.

// (2) Sort list1 and list2 using the sort method.

// (3) Compare the corresponding elements from list1 and list2.

// return false, if not match. Return true if all matches.

}

}

User Gates VP
by
3.2k points