Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (vkp) v1.0

Wiki Markup
According to the Java API \[[API 2006|AA. JavaBibliography#API References#API 06]\] class {{java.lang.Object}} documentation:

...

Wiki Markup
This compliant solution shows how the {{hashCode()}} method can be overridden so that the same value is generated for any two instances that compare equal when {{Object.equals()}} is used. Bloch discusses the recipe to generate such a hash function in good detail \[[Bloch 2008|AA. JavaBibliography#Bloch References#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 = 7;
    result = 37 * result + number;
    return result;
  }

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

...

Wiki Markup
\[[API 2006|AA. Java References#APIBibliography#API 06]\] [Class Object|http://java.sun.com/javase/6/docs/api/java/lang/Object.html]
\[[Bloch 2008|AA. Java References#BlochBibliography#Bloch 08]\] Item 9: Always override {{hashCode}} when you override {{equals}}
\[[MITRE 2009|AA. Java References#MITREBibliography#MITRE 09]\] [CWE ID 581|http://cwe.mitre.org/data/definitions/581.html] "Object Model Violation: Just One of Equals and Hashcode Defined"

...