Versions Compared

Key

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

Wiki Markup
Classes 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()}} method must produce the same integer result when the {{hashCode()}} method is invoked on the objects \[[API 2006|AA. Bibliography#APIReferences#API 06]\]. 

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.

...

Wiki Markup
This 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#BlochReferences#Bloch 08]\].

Code Block
bgColor#ccccff
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 = 17;
    result = 31 * 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)));
  }
}

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a63b31fe94f8df73-3c244913-459b4cc3-9414b7e1-3935bc080f783b6760786459"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API References#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="b1c524d4eb00ed82-6e04f496-4e3a4c09-8599a6ac-8acf676794a441804de7e916"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch References#Bloch 08]]

Item 9. Always override hashCode when you override equals

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

...