...
Code Block | ||
---|---|---|
| ||
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""Java"); // Assuming Integer.MAX_VALUE is the largest number for card System.out.println(m.get(new CreditCard(100))); } } |
...
Code Block | ||
---|---|---|
| ||
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 m = new HashMap(); m.put(new CreditCard(100), "Java""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 |
---|
\[[API 06|AA. Java References#API 06]\] [Class Object|http://java.sun.com/javase/6/docs/api/java/lang/Object.html] \[[Bloch 08|AA. Java References#Bloch 08]\] Item 9: Always override {{hashCode}} when you override {{equals}} \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 581|http://cwe.mitre.org/data/definitions/581.html] ""Object Model Violation: Just One of Equals and Hashcode Defined"" |
...
MET30-J. Follow the general contract while overriding the equals method 12. Methods (MET) MET32-J. Ensure that constructors do not call overridable methods