比较2D数组

Ade*_*e A 1 java arrays multidimensional-array

我试图通过使用它来比较两个2D阵列.但我一直得到" 阵列不一样. "即使它们是相同的.

     int i;
     int j = 0;
     int k;
     int l;

List<Integer> list = new ArrayList<Integer>();
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> zero = new ArrayList<Integer>();

 for ( i = 1; i <= 16; i++) {
    list.add(i);


}

//System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Collections.shuffle(list.subList(1, 15));
System.out.println(list);

Collections.replaceAll(list, 16, 0);
   System.out.println(list);


// System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]

int[][] a2 = new int[4][4];
int [][] a3 = new int[4][4];
for ( i = 0; i < 4; i++) {
    for ( j = 0;  j< 4; j++) {


        a2[i][j] = list.get(i*4 + j);
        a3[i][j] = list.get(i*4 + j);
    }

}
for (int[] row : a2) {
System.out.print("[");
for (   int a : row)
    System.out.printf("%4d", a);
System.out.println("]");
}
for (int[] row : a3) {
System.out.print("[");
for (   int a : row)
    System.out.printf("%4d", a);
System.out.println("]");
}
 boolean check1 = Arrays.equals(a2, a3);
if(check1 == false)
System.out.println("Arrays are not same.");
else
System.out.println("Both Arrays are same.");
Run Code Online (Sandbox Code Playgroud)

我也不能这样做.boolean check1 = Arrays.equals(a2 [i] [j],a3 [i] [j]);

Ted*_*opp 8

第一个不起作用,因为二维int数组实际上是一个数组数组(即一个对象数组).Arrays.equals()对象数组的方法用于equals()测试相应的元素是否相等.不幸的是,对于您的代码,equals()数组是默认Object实现:它们equal()只有在它们是相同的对象时才是.在你的情况下,他们不是.

在第二种情况下,当您编码Arrays.equals并传递两个int值时,编译器无法将其与Arrays该类的任何签名匹配.

检查相等性的一种方法是使用deepEquals:

boolean check1 = Arrays.deepEquals(a2, a3);
Run Code Online (Sandbox Code Playgroud)

另一种方法是显式迭代外部数组:

boolean check1 = true;
for (int i = 0; check1 && i < a2.length; ++i) {
    check1 = Arrays.equals(a2[i], a3[i]);
}
Run Code Online (Sandbox Code Playgroud)