Object Model Violation: Just One of Equals and Hashcode Defined

Draft Variant
Structure: Simple
Description

This vulnerability occurs when a Java class defines either the equals() method or the hashCode() method, but not both, breaking a fundamental contract of object equality.

Extended Description

In Java, the `equals()` and `hashCode()` methods work as a pair to define object identity for collections like `HashMap` and `HashSet`. When you override only one of these methods, you violate a core rule: if two objects are considered equal by the `equals()` method, they must return the same `hashCode()` value. Failing to uphold this contract causes unpredictable behavior in hash-based collections, leading to objects that are 'equal' being stored separately, becoming impossible to retrieve, or causing duplicate entries. To fix this, always override both methods together, ensuring their logic is based on the same set of object attributes. Use your IDE's generator or a library like Lombok to maintain consistency. This ensures your objects behave correctly in all standard Java collections and prevents subtle, hard-to-debug errors in your application's data handling.

Common Consequences 1
Scope: IntegrityOther

Impact: Other

If this invariant is not upheld, it is likely to cause trouble if objects of this class are stored in a collection. If the objects of the class in question are used as a key in a Hashtable or if they are inserted into a Map or Set, it is critical that equal objects have equal hashcodes.

Detection Methods 1
Automated Static AnalysisHigh
Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)
Potential Mitigations 1
Phase: Implementation
Both Equals() and Hashcode() should be defined.
Applicable Platforms
Languages:
Java : Undetermined
Modes of Introduction
Implementation
Taxonomy Mapping
  • The CERT Oracle Secure Coding Standard for Java (2011)