Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Dropped redundant sentence from intro; refined evaluation of Automated Detection.

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.

Code Block
bgColor#FFCCCC

public void arrayEqualsExample() {
  int[] arr1 = new int[20]; // initialized to 0
  int[] arr2 = new int[20]; // initialized to 0
  arr1.equals(arr2); // false
}

...

This compliant solution compares the two arrays using the two-argument Arrays.equals() method.

Code Block
bgColor#ccccff

public void arrayEqualsExample() {
  int[] arr1 = new int[20]; // initialized to 0
  int[] arr2 = new int[20]; // initialized to 0
  Arrays.equals(arr1, arr2); // true
}

...

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 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)