Details
-
Type:
Bug Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:None
-
Message:Add a "hashCode()" method to "className" or remove it from this hash.
-
Default Severity:Major
-
Impact:Low
-
Likelihood:High
-
Covered Languages:Java
-
Remediation Function:Constant/Issue
-
Constant Cost:15min
-
Analysis Scope:Main Sources
-
Implementation details:
-
FindBugs:HE_USE_OF_UNHASHABLE_CLASS, HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS
Description
Because Object implements hashCode, any Java class can be put into a hash structure. However, classes that define equals(Object) but not hashCode() aren't truly hash-able because instances that are equivalent according to the equals method can return different hashes.
Noncompliant Code Example
public class Student { // no hashCode() method; not hash-able // ... public boolean equals(Object o) { // ... } } public class School { private Map<Student, Integer> studentBody = // okay so far new HashTable<Student, Integer>(); // Noncompliant // ...
Compliant Solution
public class Student { // has hashCode() method; hash-able // ... public boolean equals(Object o) { // ... } public int hashCode() { // ... } } public class School { private Map<Student, Integer> studentBody = new HashTable<Student, Integer>(); // ...
Attachments
Issue Links
- is implemented by
-
SONARJAVA-1600 Rule S2141: Classes that don't define "hashCode()" should not be used in hashes
-
- Closed
-
- is related to
-
SONARJAVA-3449 FP on S2141 when equals() without default implementation is defined in an interface
-
- Closed
-