Arrays do not fail to override class Object
's equals()
method. Consequently, ; the default implementation of the equals()
method simply applied to arrays compares the array references instead of rather than the contents of the arrays. If only the references need to be compared, it is better to use relational operators, such as When testing reference equality, prefer the reference equality operators, ==
and !=
. Vulnerabilities can result, for instance, when two arrays containing signers are compared incorrectlyInappropriate use of the equals()
method may lead to unexpected results.
Noncompliant Code Example
This noncompliant code example incorrectly uses the Object.equals()
method to compare two arrays.
Code Block | ||
---|---|---|
| ||
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.
Code Block | ||
---|---|---|
| ||
Arrays.equals(arr1, arr2); // true |
Risk Assessment
Using the equals()
method or relational operators to compare array contents can produce incorrect results, which may lead to vulnerabilities.
Guideline | 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 in ideal case equal method should have been used. The "==" operator may consider objects different when the equals method considers them the same.
Static detection of attempts to use array_object.equals(...)
appears to be straightforward.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
Wiki Markup |
---|
\[[API 2006|AA. Bibliography#API 06]\] [Class {{Arrays}}|http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html] |
...
EXP01-J. Avoid comparing objects using reference equality operators 04. Expressions (EXP) EXP03-J. Do not use the equal and not equal operators to compare boxed primitives