Comparing arrays for equality

suggest change

Array types inherit their equals() (and hashCode()) implementations from java.lang.Object, so equals() will only return true when comparing against the exact same array object. To compare arrays for equality based on their values, use java.util.Arrays.equals, which is overloaded for all array types.

int[] a = new int[]{1, 2, 3};
int[] b = new int[]{1, 2, 3};
System.out.println(a.equals(b)); //prints "false" because a and b refer to different objects
System.out.println(Arrays.equals(a, b)); //prints "true" because the elements of a and b have the same values

When the element type is a reference type, Arrays.equals() calls equals() on the array elements to determine equality. In particular, if the element type is itself an array type, identity comparison will be used. To compare multidimensional arrays for equality, use Arrays.deepEquals() instead as below:

int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };

Object[] aObject = { a }; // aObject contains one element
Object[] bObject = { b }; // bObject contains one element

System.out.println(Arrays.equals(aObject, bObject)); // false
System.out.println(Arrays.deepEquals(aObject, bObject));// true

Because sets and maps use equals() and hashCode(), arrays are generally not useful as set elements or map keys. Either wrap them in a helper class that implements equals() and hashCode() in terms of the array elements, or convert them to List instances and store the lists.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents