Versions Compared

Key

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

...

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 m = new HashMap();
    m.put(new CreditCard(100), "Java");
    System.out.println(m.get(new CreditCard(100)));
  }
}

Compliant Solution

Wiki Markup
This compliant solution shows how {{hashCode}} can be overridden so that the same value is generated for an instance. The recipe to generate such a hash function is described
in Effective Java Language Programming, Item 8
 in \[[Bloch 08|AA. Java References#Bloch 08]\] Item 9: Always override {{hashCode}} when you override {{equals}}.

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 = 7;
    result = 37*result + number;
    return result;
  }

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

...

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

References

Wiki Markup
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 9: Always override {{hashCode}} when you override {{equals}}
\[[API 06|AA. Java References#API 06]\] [Class Object|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html]
Effective Programming in Java. Item 8
java.lang.Object Documentation