I need to create a method to check the elements of two arrays and determine if they are equal..
Printable View
I need to create a method to check the elements of two arrays and determine if they are equal..
If the order matters as well, you can do it manually by iterating through each array comparing each value at position x, or using the Class Arrays equals function. If the arrays may be out of order you can do it manually by taking each value in the first array, and searching the second for that value, returning false if it cannot be found, or true at the end of the iteration if all were found. Alternatively, you could sort the arrays and use the Arrays object to compare
The order is not important all, Here is what i have tried using but i get an illegal start to expression error
for the if statement... Please help me set something up im really lost...
Quote:
boolean check = Arrays.equals(setA, setB);
if (check == true){
System.out.println("Arrays are same.");
else
System.out.println("Both Arrays are not same.");
}
You are missing a pair of brackets in the code you posted. Be careful if order does not matter and you wish to check if each array contains the same SET of values (as opposed to SET and SEQUENCE), for example consider the following arrays:
int array1[] = {1,2,3,4};
int array2[] = {1,2,3,4};
int array3[] = {2,1,3,4};
Arrays.equals() will return true when comparing array1 and array2, but false when comparing array1 to array3 - even though thesy contain the same values (because they are out of order).
If you are truly confused, I recommend going back to the basics
Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)
I understand that part. Now what if the elements within the array are read in by using a scanner(user input). I can i compare those elements which i do not know or are not fixed.