日期:2014-05-20  浏览次数:20774 次

如何通过代码判定一个多维数组相等
int a[][]={{1,2},{3,4}}
int b[][]={{1,2},{3,4}}
谢谢各位

------解决方案--------------------

------解决方案--------------------
遍历,一个一个元素比较
------解决方案--------------------
1. 首先看他们的维数是否相等 m n比较一下
2.对每个位置的元素循环比较
------解决方案--------------------
探讨
用ARRAYS.equals判断

------解决方案--------------------
先比较数组大小!
IF
一样的话
就用循环取出来,然后直接比就得了,
在循环中如果有一个不相等的话,就return false

------解决方案--------------------
Java code

public class Test {
    public static void main(String arg[]) {
        int a[][] = { { 1, 2 }, { 3, 4 } };
        int b[][] = { { 1, 2 }, { 3, 4 } };
        int c[][] = { { 1, 2 }, { 3, 5 } };
        System.out.println("a=b? the result is "+compare(a,b));
        System.out.println("a=c? the result is "+compare(a,c));
    }

    public static boolean compare(int t1[][], int t2[][]) {
        boolean result = true;
        if (t1.length != t2.length) {
            result = false;
        } else {
            for (int i = 0; i < t1.length; i++) {
                for (int j = 0; j < t1[i].length; j++) {
                    if (t1[i][j] != t2[i][j]) {
                        result = false;
                    }
                }
            }
        }

        return result;
    }
}

------解决方案--------------------
public static void main(String [] args) throws Exception

int [][] a = new int[][]{{3,4,5},{2,3}};
int [][] b = new int[][]{{3,4,5},{2,3}};
int [][] c = new int[][]{{3,4,5},{1,3}};

System.out.println(equals(a,b));
System.out.println(equals(a,c));
}

public static boolean equals(int [][] a, int [][] b)
{
boolean result = true;
if(a.length == b.length)
{
for(int i = 0; i < a.length; i ++)
{
int [] ai = a[i];
int [] bi = b[i];
if(! Arrays.equals(ai, bi))
{
result = false;
break;
}
}
}else
{
result = false;
}
return result;
}
------解决方案--------------------
遍历比较