有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何比较二维(或嵌套)Java数组?

来自数组的Java文档。等于(对象[]a,对象[]a2)

Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

但是当我运行下面的程序时,它将false打印为输出

那么,Array类的meanequals方法对多维数组不起作用吗

我可以使用什么API来实现true作为下面程序的结果

public class Test {
    public static void main(String[] args) {
        String[][] rows1 = { new String[] { "a", "a" } };

        String[][] rows2 = { new String[] { "a", "a" } };

        System.out.println("Arrays.equals() = " + Arrays.equals(rows1, rows2));

    }
}

共 (4) 个答案

  1. # 2 楼答案

    Arrays.deepEquals()

    以下是Arrays.equals不起作用的原因。正如文档所说,数组必须具有相同数量的元素,并且元素必须相等。数组的元素数相同:1。每个元素是另一个数组

    但是,将这些数组与常规的equals方法进行比较。对于任何对象,如果对象不重写为Object定义的equals方法,则使用为Object定义的equals方法,这与==。数组不重写equals(它们也不重写toString(),这就是为什么我们必须使用Arrays.toString()来格式化数组)

    Arrays.deepEquals()对元素是数组时进行特殊检查,然后使用递归Arrays.deepEquals()测试这些数组是否相等

  2. # 3 楼答案

    您正在比较二维数组,这意味着这些数组的元素本身就是数组。因此,当比较元素时(使用Objectequals),返回false,因为Objectequals比较Object引用

    改用Arrays.deepEquals

    从Javadoc:

    boolean java.util.Arrays.deepEquals(Object[] a1, Object[] a2)

    Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object [], Object []) method, this method is appropriate for use with nested arrays of arbitrary depth.

  3. # 4 楼答案

    它无法按预期工作,因为您正在使用new初始化两个不同的对象

    来自Java文档:

    boolean java.util.Arrays.equals(Object[] a, Object[] a2)

    Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objects e1 and e2 are considered equal if (e1==null ? e2==null : e1.equals(e2)). In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

    Parameters: a one array to be tested for equality a2 the other array to be tested for equality Returns: true if the two arrays are equal