Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals(). Furthermore, this method must follow the general contract for equals(), as specified by the Java Language Specification [JLS 20052015].

An object is characterized both by its identity (location in memory) and by its state (actual data). The == operator compares only the identities of two objects (to check whether the references refer to the same object); the equals() method defined in java.lang.Object can be overridden to compare the state as well. When a class defines an equals() method, it implies that the method compares state. When the class lacks a customized equals() method (either locally declared or inherited from a parent class), it uses the default Object.equals() implementation inherited from Object. The default Object.equals() implementation compares only the references and may produce unexpected results.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET08-J

Low

Unlikely

Medium

P2

L3

Related Guidelines

MITRE CWE

CWE-697. , Insufficient comparisonComparison

Bibliography

[API 2006]

Method equals()

[Bloch 2008]

Item 8. , "Obey the general contract when overriding equalsGeneral Contract When Overriding equals"

[Darwin 2004]

Section 9.2, "Overriding the equals Method"

[Harold 1997]

Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)"

[Sun 2006]

Determining If Two Keys Are Equal (JCA Reference Guide)

[Techtalk 2007]

"More Joy of Sets"

 

...