先比较数组大小! IF 一样的话 就用循环取出来,然后直接比就得了, 在循环中如果有一个不相等的话,就return false
能否给一下代码啊,因为对JAVA的语法不是很熟
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}};
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; }
用 Arrays.equals 不行,它只会比较一维所包含的构成二维的各个数组的引用是否相同,不会比较二维的元素。
IF
一样的话
就用循环取出来,然后直接比就得了,
在循环中如果有一个不相等的话,就return false
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;
}
}
{
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;
}