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?
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”.
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?
Use
deepEquals(Object[], Object[]).Since an
int[]is aninstanceof Object, anint[][]is aninstanceof Object[].As to why
Arrays.equalsdoesn’t “work” for two dimensional arrays, it can be explained step by step as follows:For arrays,
equalsis defined in terms of object identityThis is because arrays inherit their
equalsfrom their common superclass,Object.Often we really want value equality for arrays, of course, which is why
java.util.Arraysprovides thestaticutility methodequals(int[], int[]).Array of arrays in Java
int[]is aninstanceof Objectint[][]is aninstanceof Object[]int[][]is NOT aninstanceof int[]Java doesn’t really have two dimensional arrays. It doesn’t even really have multidimensional arrays. Java has array of arrays.
java.util.Arrays.equalsis “shallow”Now consider this snippet:
Here are the facts:
Object[]int[] { 1 }int[] { 2, 3 }.Object[]instancesint[]instancesIt should be clear from the previous point that this invokes
Arrays.equals(Object[], Object[])overload. From the API:Now it should be clear why the above snippet prints
"false"; it’s because the elements of theObject[]arrays are not equal by the above definition (since anint[]has itsequalsdefined by object identity).java.util.Arrays.deepEqualsis “deep”In contrast, here’s what
Arrays.deepEquals(Object[], Object[])does:On
Arrays.toStringandArrays.deepToStringIt’s worth noting the analogy between these two methods and what we’ve discussed so far with regards to nested arrays.
Again, the reasoning is similar:
Arrays.toString(Object[])treats each element as anObject, and just call itstoString()method. Arrays inherit itstoString()from their common superclassObject.If you want
java.util.Arraysto consider nested arrays, you need to usedeepToString, just like you need to usedeepEquals.