Arrays do not override the Object.equals()
method; rather, the implementation of the equals()
method compares array references rather than their contents. To compare the contents of two arrays, use the two-argument Arrays.equals()
method instead. When intentionally testing reference equality, use the reference equality operators, ==
and !=
. Inappropriate use of the equals()
method can lead to unexpected results. Consequently, programs must reserve use of the array equality operators == and != for testing whether two array references specifically refer to the same array object, and are required to use the two-argument Arrays.equals()
method for all other cases.
This rule is a specialization of EXP01-J. Do not confuse abstract object equality with 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
The Coverity Prevent Version 5.0 BAD_EQ checker can detect the instance where the == operator is being used for equality of objects when, ideally, equals()
should have been used. The == operator could consider the objects to be different, whereas the equals()
method would consider them to be the same.
Static detection of attempts to use array_object.equals(...)
appears to be straightforward.
Related Guidelines
CWE ID 595, "Comparison of Object References Instead of Object Contents" |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4d419783-b5b3-4261-8934-6f0b668949dd"><ac:plain-text-body><![CDATA[ |
[[API 2006 |
AA. Bibliography#API 06]] |
[Class |
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html] |
]]></ac:plain-text-body></ac:structured-macro> |
EXP01-J. Do not confuse abstract object equality with reference equality 02. Expressions (EXP)