You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 33 Next »

Arrays do not override the Object.equals() method; the implementation of the equals() method for arrays compares the array references rather than the contents of the arrays. Use the two-argument Arrays.equals() method to compare the contents of two array. When intentionally testing reference equality, use the reference equality operators, == and !=; inappropriate 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.

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.

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.

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, ideally, equals() should have been used. The "==" operator could consider objects different when equals() 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

[[API 2006]] Class Arrays


EXP01-J. Do not confuse abstract object equality with reference equality      02. Expressions (EXP)      

  • No labels