我有以下二维数组:
String[][] array1 = {{"hello", "hi"}{"bye", "two"}};
String[][] array2 = {{"hello", "hi", "three"}{"bye", "maybe", "third"}, {"3", "rd", "Element"}};
String[][] array3 = {{"hello", "hi"}{"bye", "two"}};
我如何检查它们是否具有相同的值(不同的尺寸)?感谢
答案 0 :(得分:1)
public static boolean deepEquals(Object[] a1, Object[] a2)
如果两个指定的数组彼此非常相等,则返回true。与
equals(Object[],Object[])
方法不同,此方法适用于任意深度的嵌套数组。如果两个数组引用都为null,或者它们引用包含相同数量元素的数组并且两个数组中所有相应的元素对完全相等,则认为两个数组引用非常相等。
如果满足以下任何条件,则两个可能为空的元素
e1
和e2
完全相同:
- e1和e2都是对象引用类型的数组,而Arrays.deepEquals(e1,e2)将返回true
- e1和e2是相同基元类型的数组,Arrays.equals(e1,e2)的相应重载将返回true。
- e1 == e2
- e1.equals(e2)将返回true。
请注意,此定义允许任何深度的null元素。
如果任一指定的数组直接或间接通过一个或多个数组级别将自身包含为元素,则此方法的行为是未定义的。
答案 1 :(得分:0)
您也可以创建自己的方法:
public boolean compare(String[][] a, String[][] b){
boolean result = true;
int outer = Math.max(a.length, b.length);
int inner = Math.max(a[0].length, b[0].length);
for(int i = 0; i<outer; i++){
for(int j = 0; j<inner; j++){
if(i < a.length && i < b.length && j < a[0].length && j < b[0].length){
if(!a[i][j].equals(b[i][j])){
result = false;
}
}
}
}
return result;
}