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

Compare with Current View Page History

« Previous Version 51 Next »

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.

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 Array.equals(), as well as calls to Object.equals() and invocations of the == operator is straightforward.

Related Guidelines

MITRE CWE

CWE-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="2449affb-3c43-4c2b-afb0-ed130be6b892"><ac:plain-text-body><![CDATA[

[[API 2006

AA. References#API 06]]

[Class Arrays

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html]

]]></ac:plain-text-body></ac:structured-macro>


EXP01-J. Never dereference null pointers      02. Expressions (EXP)      

  • No labels