Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The arrays list1 and list2 are identical, if they contain the same elements (pos

ID: 3685930 • Letter: T

Question

The arrays list1 and list2 are identical, if they contain the same elements (possibly in different order). Write a method that returns true if list1 and list2 are identical, using the following header: public static boolean sameValues (int[] list1, int[] list2)

Write a test program in Java that prompts user to enter two lists of integers and displays whether the two are strictly identical. Here are the sample runs. Note that the first number in the input indicated the number of elements in the list; it is not part of the list. Create a do-while loop that allows the user to repeat upon request

Explanation / Answer

IntArraysIdentical.java


import java.util.Arrays;

public class IntArraysIdentical {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       java.util.Scanner in = new java.util.Scanner(System.in);
       int i = 0;
       System.out.println("Please enter the array size : ");
       int n = in.nextInt();
       int arr1[] = new int[n];
       int arr2[] = new int[n];
       do{
       System.out.println("Please enter first array element ");
           arr1[i] = in.nextInt();
       System.out.println("Please enter second array element ");
           arr2[i] = in.nextInt();
       i++;
       } while(i < n);
       System.out.println("First array Elements : "+Arrays.toString(arr1));
       System.out.println("Second array Elements : "+Arrays.toString(arr2));
       boolean status = sameValues(arr1, arr2);
       if(status == true)
       System.out.println("Both arrays are same");
       else
       System.out.println("Both arrays are not same");
   }
   private static boolean sameValues(int[] list1, int [] list2){

   if(list1 == null || list2 == null){

   return false;
   }
   if(list1.length != list2.length)
   {
   return false;
   }
   else{

   Arrays.sort(list1);
   Arrays.sort(list2);

   return Arrays.equals(list1, list2);
   }

   }  
}

Output

Please enter the array size :
5
Please enter first array element
1
Please enter second array element
2
Please enter first array element
2
Please enter second array element
1
Please enter first array element
3
Please enter second array element
4
Please enter first array element
4
Please enter second array element
3
Please enter first array element
5
Please enter second array element
5
First array Elements : [1, 2, 3, 4, 5]
Second array Elements : [2, 1, 4, 3, 5]
Both arrays are same

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote