CRITICAL
Rule Definition
Often classes are used in HashMap to provide an efficient storage and retrieval. The Java platform architects anticipated the importance of hash-based collection classes -- such as Hashtable, HashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive.
If your java class is used or can be used in a hash-based collection, override both of these methods to avoid any issues that can be painful to find when the issue appear in production because the error is not in the code that is present, but in the code that is absent.
Remediation
Override both methods.
Violation Code Sample
class Example {
int id;
public int getId() {
return id;
}
public boolean equals(Object obj) {
return (obj instanceof Example
&& id == ((Example) obj).getId());
}
// VIOLATION: missing hashCode()
}
Fixed Code Sample
class Example {
int id;
public int getId() {
return id;
}
public boolean equals(Object obj) {
return (obj instanceof Example
&& id == ((Example) obj).getId());
}
public int hashCode() { // FIXED
return id/10;
}
}
Reference
http://www-128.ibm.com/developerworks/java/library/j-jtp05273.html
Related Technologies
JEE
Technical Criterion
CWE-1097 - Persistent Storable Data Element without Associated Comparison Control Element
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.