Versions Compared

Key

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

Wiki MarkupClasses that override the {{Object.equals()}} method must also override the {{Object.hashCode()}} method. The {{java.lang.Object}} class requires that any two objects that compare equal using the {{equals(Object)}} method must produce the same integer result when the {{hashCode()}} method is invoked on the objects \ [[API 2006|AA. Bibliography#API 06]\API 2014].

The equals() method is used to determine logical equivalence between object instances. Consequently, the hashCode() method must return the same value for all equivalent objects. Failure to follow this contract is a common source of defects.

...

This noncompliant code example associates credit card numbers with strings using a HashMap and subsequently attempts to retrieve the string value associated with a credit card number. The expected retrieved value is 4111111111111111; the actual retrieved value is null. The cause of this erroneous behavior is that the CreditCard class overrides the equals() method but fails to override the hashCode() method. Consequently, the default hashCode() method returns a different value for each object, even though the objects are logically equivalent; these differing values lead to examination of different hash buckets, which prevents the get() method from finding the intended value.

Code Block
bgColor#FFCCCC

public final class CreditCard {
  private final int number;

  public CreditCard(int number) {
    this.number = (short) number;
  }

  public boolean equals(Object o) {
    if (o == this) {
      return true;
    } 
    if (!(o instanceof CreditCard)) {
      return false;
    }
    CreditCard cc = (CreditCard)o;
    return cc.number == number; 
  }

  public static void main(String[] args) {
    Map<CreditCard, String> m = new HashMap<CreditCard, String>();
    m.put(new CreditCard(100), "4111111111111111");
    System.out.println(m.get(new CreditCard(100)));  
  }
}

The cause of this erroneous behavior is that the CreditCard class overrides the equals() method but fails to override the hashCode() method. Consequently, the default hashCode() method returns a different value for each object, even though the objects are logically equivalent; these differing values lead to examination of different buckets in the hash table, which prevents the get() method from finding the intended value.
Note that by specifying the credit card number in main(), these code examples violate MSC03-J. Never hard code sensitive information for the sake of brevity.

Compliant Solution

Wiki MarkupThis compliant solution overrides the {{hashCode()}} method so that it generates the same value for any two instances that are considered to be equal by the {{equals()}} method. Bloch discusses the recipe to generate such a hash function in detail \ [[Bloch 2008|AA. Bibliography#Bloch 08]\].

Code Block
bgColor#ccccff

import java.util.Map;
import java.util.HashMap;

public final class CreditCard {
  private final int number;
  
  public CreditCard(int number) {
    this.number = (short) number;
  }

  public boolean equals(Object o) {
    if (o == this) {
      return true;
    } 
    if (!(o instanceof CreditCard)) {
      return false;
    }
    CreditCard cc = (CreditCard)o;
    return cc.number == number; 
  }

  public int hashCode() {
    int result = 717;
    result = 3731 * result + number;
    return result;
  }

  public static void main(String[] args) {
    Map<CreditCard, String> m = new HashMap<CreditCard, String>();
    m.put(new CreditCard(100), "4111111111111111");
    System.out.println(m.get(new CreditCard(100)));
  }
}

...

Overriding the equals() method without overriding the hashCode() method can lead to unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET13

MET09-J

low

Low

unlikely

Unlikely

high

High

P1

L3

Automated Detection

Automated detection of classes that override only one of equals() and hashcode() is straightforward. Sound static determination that the implementations of equals() and hashcode() are mutually consistent is not feasible in the general case, although heuristic techniques may be used.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

useful.

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.IDEF.EQUALSNOHC
JAVA.IDEF.HCNOEQUALS

Defines equals but not hashCode (Java)
Defines hashCode but not equals (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.MET09.OVERRIDEOverride 'Object.hashCode()' when you override 'Object.equals()' and vice versa
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6049
SonarQube
Include Page
SonarQube_V
SonarQube_V

S1206

"equals(Object obj)" and "hashCode()" should be overridden in pairs

Related Guidelines

MITRE CWE

CWE-581,

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9b0c3828-031e-433e-b2b5-f688c0bca907"><ac:plain-text-body><![CDATA[

[[MITRE 2009

AA. Bibliography#MITRE 09]]

[CWE-581

http://cwe.mitre.org/data/definitions/581.html] "

Object Model Violation: Just One of

Equals

equals and

Hashcode

hashcode Defined

"

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

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="19031275-ecb0-4c03-a08e-4f57acb690ea"><ac:plain-text-body><![CDATA

[

[[API 2006

AA. Bibliography#API 06]]

[Class Object

http://java.sun.com/javase/6/docs/api/java/lang/Object.html]

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="15a7abc0-b5a4-4157-a525-bee3551176bd"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 9: Always override hashCode when you override equals

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

API 2014]

Class Object

[Bloch 2008]

Item 9, "Always Override hashCode When You Override equals"


...

Image Added Image Added MET08-J. Ensure objects that are equated are equatable      05. Methods (MET)      Image Modified