首先定义两个数组
int[] arry1={1,2,3,4,5,6};
int[] arry2={1,2,3,4,5,6};
两个数组相等的依据是,官方注释说到:In other words, two arrays are equal if they contain
the same elements in the same order. Also,two array references are
considered equal if both are null. 谷歌翻译:换句话说,如果两个数组包含相同顺序的相同元素,则它们相等。
另外,如果两个数组引用均为 null ,则认为它们相等
。
public class Main {
public static void main(String[] args) {
System.out.println(matchArry());
}
private static boolean matchArry() {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 4, 5};
if (arr1.length == arr2.length) {
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
return false;
}
}
而对于无序数组来说,当只需要比较两个数组的内容是否相同而不需要考虑顺序时,只需先把数组顺排即可
public class main {
public static void main(String[] args) {
int[] artg={3,1,6,2,5,4};
int[] aty={1,2,4,3,6,5};
Arrays.sort(artg); //对两数组进行排序
Arrays.sort(aty);
if (Arrays.equals(artg,aty)){
System.out.println("true");
}else{
System.out.println("false");
}
}
}
代码量减少了一半,而且对无序数组也适用!