应使用 Arrays.deepEquals() 比较多维或嵌套数组内容是否相等,因其递归比较各层元素;Arrays.equals() 仅浅层比较引用,故对多维数组恒返回 false。
直接用 Arrays.deepEquals() 就行,不用自己写嵌套循环。它专为多维或嵌套数组设计,能真正比“内容是否一样”,而不是看是不是同一个对象。
Arrays.equals() 只比较一层:遇到 int[]、String[] 这类元素时,直接用 == 判断引用是否相同。而不同 new 出来的二维数组,哪怕内容完全一样,内部的行数组也是不同对象,所以结果恒为 false。
Arrays.equals(new int[][]{{1,2}}, new int[][]{{1,2}}) → false
int[] 引用(a[0] == b[0]),不是它们的内容它会逐层递归:遇到数组类型元素(如 int[]、String[][]、Object[] 中的子数组),自动调用对应维度的 deepEquals 或 equals;遇到普通对象(如 String、Date),则调用其 equals() 方法。
int[][][]、Object[]{new int[]{1}, "hello"} 都能比null 元素视为相等;null 和非 null 视为不等equals()
不是所有“看起来像数组”的情况都适合 deepEquals。它只管数组结构本身,不深入对象字段。
int[2][3] 和一个 int[2][3][4] 传进去会抛 IllegalArgumentException
Person[] 中每个 Person 有个 int[] scores 字段,deepEquals 不会去比 scores 的内容——除非 Person.equals() 自己处理了Arrays.equals() 更快更直接这些写法都能得到预期的 true:
Arrays.deepEquals(new int[][]{{1,2},{3}}, new int[][]{{1,2},{3}})Arrays.deepEquals(new String[][]{{"a"},{"b","c"}}, new String[][]{{"a"},{"b","c"}})Object[] a = {new int[]{1,2}, "x"}; Object[] b = {new int[]{1,2}, "x"}; Arrays.deepEquals(a, b)