Java: How to test on array equality?

user905686 picture user905686 · Nov 8, 2011 · Viewed 60.1k times · Source

Why is the following code printing "Different."?

boolean[][] a = { {false,true}, {true,false} };
boolean[][] b = { {false,true}, {true,false} };

if (Arrays.equals(a, b) || a == b)
    System.out.println("Equal.");
else
    System.out.println("Different.");

Answer

aioobe picture aioobe · Nov 8, 2011

Why is the following code printing "Different."?

Because Arrays.equals performs a shallow comparison. Since arrays inherit their equals-method from Object, an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays.

If you change to Arrays.deepEquals it will print "Equal." as expected.