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

Compare with Current View Page History

« Previous Version 57 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.

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 always possible to statically resolve the class of a method invocation's target. Therefore, there can exist code that invokes Object.equals for which we cannot decide whether or not the target is an array type.

Also, it is not possible to determine whether or not use of reference equality (operators == and !=) is intentional.

Related Guidelines

MITRE CWE

CWE-595. Comparison of object references instead of object contents

Bibliography

 

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

  • No labels