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

Compare with Current View Page History

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

Tool
Version
Checker
Description
Coverity7.5

BAD_EQ

FB.EQ_ABSTRACT_SELF

FB.EQ_ALWAYS_FALSE

FB.EQ_ALWAYS_TRUE

FB.EQ_CHECK_FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS

FB.EQ_COMPARETO_USE_OBJECT_ EQUALS

FB.EQ_COMPARING_CLASS_NAMES

FB.EQ_DOESNT_OVERRIDE_EQUALS

FB.EQ_DONT_DEFINE_EQUALS_ FOR_ENUM

FB.EQ_GETCLASS_AND_CLASS_ CONSTANT

FB.EQ_OTHER_NO_OBJECT

FB.EQ_OTHER_USE_OBJECT

FB.EQ_OVERRIDING_EQUALS_ NOT_SYMMETRIC

FB.EQ_SELF_NO_OBJECT

FB.EQ_SELF_USE_OBJECT

FB.EQ_UNUSUAL

Implemented

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