+ 7
How to check the equality of two arrays in Java?
Please Help!!!
5 ответов
+ 5
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("Is array 1 equal to array 2?? "
+Arrays.equals(ary, ary1));
System.out.println("Is array 1 equal to array 3?? "
+Arrays.equals(ary, ary2));
}
}
+ 4
use the method equals in the Arrays class
for example:
int [ ] arr1 = {1, 2, 3};
int [ ] arr2 = {1, 2};
if (Arrays.equals (arr1, arr2)) {
System.out.println("true");
}
else {
System.out.println("false");
}
the Arrays.equals method will return true if the 2 arrays passed in the parameters are the same, false if not
In this case it will return false, so the else statement will be executed (it will print false to the screen)
+ 3
by equality you mean same elements and the same order of elements
or just same elememts with no consideration to their order?
+ 3
The best way to do that: Arrays.equals(array1, array2);
make sure that you sort both arrays at first: Arrays.sort(array);
+ 1
check element by element using Loop, set flag=1 if any element is mismatched.