How to compare two-dimensional (or nested) Java Arrays?

Joker :

From the Java docs for 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.

But when I ran the program below it is printing false as output.

So, Does the mean equals method of the Array class not work for multidimensional arrays?

What API can I use to achieve true as the result in the program below?

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));

    }
}
Eran :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437055&siteId=1