Arrays do not override the Object.equals()
method; the implementation of the equals()
method compares array references rather than their contents. Programs must use the two-argument Arrays.equals()
method to compare the contents of two arrays. Programs must use the reference equality operators, ==
and !=
, when intentionally testing reference equality. Programs also must not use the array equals()
method because it can lead to unexpected results.
Noncompliant Code Example
This noncompliant code example incorrectly uses the Object.equals()
method to compare two arrays.
Code Block | ||
---|---|---|
| ||
public void arrayEqualsExample() {
int[] arr1 = new int[20]; // initialized to 0
int[] arr2 = new int[20]; // initialized to 0
arr1.equals(arr2); // false
}
|
...
This compliant solution compares the two arrays using the two-argument Arrays.equals()
method.
Code Block | ||
---|---|---|
| ||
public void arrayEqualsExample() {
int[] arr1 = new int[20]; // initialized to 0
int[] arr2 = new int[20]; // initialized to 0
Arrays.equals(arr1, arr2); // true
}
|
...
Static detection of calls to Arrays.equals()
, as well as calls to Object.equals()
and invocations of the ==
operator is straightforward. However, it is not possible to determine whether or not use of reference equality (operators == and !=) is intentional.
Related Guidelines
Bibliography
EXP01-J. Never dereference null pointers 02. Expressions (EXP)