Java Arrays.equals() 为二维数组返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2721033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:05:00  来源:igfitidea点击:

Java Arrays.equals() returns false for two dimensional arrays

javaarrays

提问by Achilles

I was just curious to know - why does Arrays.equals(double[][], double[][]) return false? when in fact the arrays have the same number of elements and each element is the same?

我只是想知道 - 为什么 Arrays.equals(double[][], double[][]) 返回 false?当实际上数组具有相同数量的元素并且每个元素都相同时?

For example I performed the following test.

例如,我进行了以下测试。

double[][] a,  b;
int size =5;

a=new double[size][size];
b=new double[size][size];

for( int i = 0; i < size; i++ )
    for( int j = 0; j < size; j++ ) {
        a[i][j]=1.0;
        b[i][j]=1.0;
    }

if(Arrays.equals(a, b))
    System.out.println("Equal");
else
    System.out.println("Not-equal");

Returns false and prints "Not-equal".

返回 false 并打印“Not-equal”。

on the other hand, if I have something like this:

另一方面,如果我有这样的事情:

double[] a,  b;
int size =5;

a=new double[size];
b=new double[size];

for( int i = 0; i < size; i++ ){
    a[i]=1.0;
    b[i]=1.0;
} 

if(Arrays.equals(a, b))
    System.out.println("Equal");
else
    System.out.println("Not-equal");

returns true and prints "Equal". Does the method only work with single dimensions? if so, is there something similar for multi-dimensional arrays in Java?

返回 true 并打印“Equal”。该方法是否仅适用于单一维度?如果是这样,Java 中的多维数组是否有类似的东西?

采纳答案by polygenelubricants

Use deepEquals(Object[], Object[]).

使用deepEquals(Object[], Object[]).

Returns trueif the two specified arrays are deeply equalto one another.

true如果两个指定的数组彼此完全相等,则返回。

Since an int[]is an instanceof Object, an int[][]is an instanceof Object[].

因为 anint[]是 an instanceof Object,所以 anint[][]是 an instanceof Object[]



As to whyArrays.equalsdoesn't "work" for two dimensional arrays, it can be explained step by step as follows:

至于为什么Arrays.equals对二维数组“不起作用”,可以分步解释如下:

For arrays, equalsis defined in terms of object identity

对于数组,equals根据对象标识定义

System.out.println(
    (new int[] {1,2}).equals(new int[] {1,2})
); // prints "false"

This is because arrays inherit their equalsfrom their common superclass, Object.

这是因为数组equals从它们的公共超类Object.

Often we really want value equality for arrays, of course, which is why java.util.Arraysprovides the staticutility method equals(int[], int[]).

通常,我们确实希望数组的值相等,当然,这就是java.util.Arrays提供static实用程序方法的原因equals(int[], int[])

System.out.println(
    java.util.Arrays.equals(
        new int[] {1,2},
        new int[] {1,2}
    )
); // prints "true"

Array of arrays in Java

Java中的数组数组

  • An int[]is an instanceof Object
  • An int[][]is an instanceof Object[]
  • An int[][]is NOTan instanceof int[]
  • 一个int[]instanceof Object
  • 一个int[][]instanceof Object[]
  • 一个int[][]不是一个instanceof int[]

Java doesn't really have two dimensional arrays. It doesn't even really have multidimensional arrays. Java has array of arrays.

Java 并没有真正的二维数组。它甚至没有真正的多维数组。Java 有数组数组。

java.util.Arrays.equalsis "shallow"

java.util.Arrays.equals是“浅”

Now consider this snippet:

现在考虑这个片段:

System.out.println(
    java.util.Arrays.equals(
        new int[][] {
            { 1 },
            { 2, 3 },
        },
        new int[][] {
            { 1 },
            { 2, 3 },
        }
    )
); // prints "false"

Here are the facts:

以下是事实:

  • Each argument is an Object[]
    • The element at index 0 is an int[] { 1 }
    • The element at index 1 is an int[] { 2, 3 }.
  • There are two Object[]instances
  • There are four int[]instances
  • 每个参数都是一个 Object[]
    • 索引 0 处的元素是 int[] { 1 }
    • 索引 1 处的元素是int[] { 2, 3 }
  • 有两种Object[]情况
  • 有四种int[]情况

It should be clear from the previous point that this invokes Arrays.equals(Object[], Object[])overload. From the API:

从上一点应该很清楚,这会调用Arrays.equals(Object[], Object[])重载。从API:

Returns trueif the two specified arrays of Objectsare equal to one another. The two arrays are considered equalif both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objects e1and e2are considered equal if (e1==null ? e2==null : e1.equals(e2)).

true如果 的两个指定数组Objects彼此相等,则返回。两个阵列被认为是equal,如果两个阵列包含相同数量的元件,并且在这两个阵列元件的所有相应对是相等的。如果 ,两个对象e1e2被认为是相等的(e1==null ? e2==null : e1.equals(e2))

Now it should be clear why the above snippet prints "false"; it's because the elements of the Object[]arrays are not equal by the above definition (since an int[]has its equalsdefined by object identity).

现在应该清楚为什么上面的代码片段会打印"false";这是因为所述的元件Object[]阵列是不是由上面的定义相同(因为一个int[]具有其equals由对象标识定义)。

java.util.Arrays.deepEqualsis "deep"

java.util.Arrays.deepEquals是“深”

In contrast, here's what Arrays.deepEquals(Object[], Object[])does:

相比之下,这是做什么的Arrays.deepEquals(Object[], Object[])

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

返回true如果两个指定数组深深彼此相等。与该equals(Object[],Object[])方法不同,该方法适用于任意深度的嵌套数组。

System.out.println(
    java.util.Arrays.deepEquals(
        new int[][] {
            { 1 },
            { 2, 3 },
        },
        new int[][] {
            { 1 },
            { 2, 3 },
        }
    )
); // prints "true"


On Arrays.toStringand Arrays.deepToString

Arrays.toStringArrays.deepToString

It's worth noting the analogy between these two methods and what we've discussed so far with regards to nested arrays.

值得注意的是这两种方法之间的类比以及我们迄今为止讨论的有关嵌套数组的内容。

System.out.println(
    java.util.Arrays.toString(
        new int[][] {
            { 1 },
            { 2, 3 },
        }
    )
); // prints "[[I@187aeca, [I@e48e1b]"

System.out.println(
    java.util.Arrays.deepToString(
        new int[][] {
            { 1 },
            { 2, 3 },
        }
    )
); // prints "[[1], [2, 3]]"

Again, the reasoning is similar: Arrays.toString(Object[])treats each element as an Object, and just call its toString()method. Arrays inherit its toString()from their common superclass Object.

同样,推理是相似的:Arrays.toString(Object[])将每个元素视为一个Object,并且只调用它的toString()方法。数组toString()从它们的公共超类继承它Object

If you want java.util.Arraysto consider nested arrays, you need to use deepToString, just like you need to use deepEquals.

如果要java.util.Arrays考虑嵌套数组,则需要使用deepToString,就像需要使用deepEquals.

回答by user2209812

java does not actually have multidimensional arrays. Instead it has only single dimensional array and the multi d arrays will be arrays of this 1d arrays . String.equals() can be only performed to the basic , single block arrays and hence it doesn't work for multidimensional arrrays.

java实际上没有多维数组。相反,它只有一维数组,多维数组将是这个一维数组的数组。String.equals() 只能对基本的单块数组执行,因此它不适用于多维数组。