How to compare two-dimensional (or nested) Java Arrays?
Arrays.deepEquals()
.
Here's why Arrays.equals
doesn't work. As the doc says, the arrays have to have the same number of elements, and the elements have to be equals. The arrays do have the same number of elements: 1. Each element is another array.
However, those arrays are compared with the regular equals
method. And for any object, if the object doesn't override the equals
method defined for Object
, then the equals
method defined for Object
is used, which is the same as ==. And arrays don't override equals
(they also don't override toString()
, which is why we have to use Arrays.toString()
to format an array).
Arrays.deepEquals()
makes a special check for when elements are arrays, and then it uses a recursive Arrays.deepEquals()
to test those arrays for equality.
You are comparing two dimensional arrays, which means the elements of these arrays are themselves arrays. Therefore, when the elements are compared (using Object
's equals
), false
is returned, since Object
's equals
compares Object
references.
Use Arrays.deepEquals
instead.
From the 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.