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.
Noncompliant Code Example
This noncompliant code example incorrectly uses the Object.equals()
method to compare two arrays.
public void arrayEqualsExample() { int[] arr1 = new int[20]; // initialized to 0 int[] arr2 = new int[20]; // initialized to 0 arr1.equals(arr2); // false }
Compliant Solution
This compliant solution compares the two arrays using the two-argument Arrays.equals()
method.
public void arrayEqualsExample() { int[] arr1 = new int[20]; // initialized to 0 int[] arr2 = new int[20]; // initialized to 0 Arrays.equals(arr1, arr2); // true }
Risk Assessment
Using the equals()
method or relational operators with the intention of comparing array contents produces incorrect results, which can lead to vulnerabilities.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP02-J | low | likely | low | P9 | L2 |
Automated Detection
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)