Why Overriding hashCode Is Required When You Override equals in Java
This article explains the relationship between Java's equals and hashCode methods, outlines their contractual requirements, shows how the default implementations work, demonstrates proper overrides with code examples, and provides practical guidelines for implementing robust hashCode functions to ensure correct behavior in hash‑based collections.
Why equals and hashCode Exist
All Java classes inherit equals(Object) and hashCode() from Object. The default equals compares object references (using ==), while hashCode is a native method that returns an integer derived from the object's memory address.
equals Method
The default implementation is insufficient for most domain objects, so it is commonly overridden. For example, String overrides equals to compare character arrays when references differ:
public boolean equals(Object anObject) {
if (this == anObject) return true;
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char[] v1 = value;
char[] v2 = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i]) return false;
i++;
}
return true;
}
}
return false;
}The contract of equals requires reflexivity, symmetry, transitivity, consistency, and non‑nullity.
hashCode Method
hashCode()returns an integer used by hash‑based collections such as HashMap and HashSet. The default implementation returns a value derived from the object's address, guaranteeing distinct values for distinct objects.
For String, the overridden method computes a hash based on character values:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char[] val = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}The formula is s[0]*31^(n‑1) + s[1]*31^(n‑2) + … + s[n‑1], where s[i] is the i‑th character and n is the string length. The prime number 31 is chosen because it provides a good trade‑off between hash distribution and performance, and the JVM can optimize the multiplication.
Why hashCode Must Align with equals
Hash‑based collections first locate a bucket using hashCode. If a collision occurs, they invoke equals to determine actual equality. Therefore, if two objects are equal according to equals, they must produce the same hash code; otherwise, the collection may store duplicate keys or fail to retrieve values.
Contractual Requirements for hashCode
Repeated calls on the same object must return the same integer as long as the object’s state used in equals does not change.
If two objects are equal according to equals, their hash codes must be identical.
Unequal objects are not required to have distinct hash codes, but better distribution improves performance.
Guidelines for Overriding hashCode (Effective Java)
Start with a non‑zero constant, e.g., int result = 17;.
For each field used in equals, compute a contribution:
boolean → f ? 1 : 0 byte, char, short, int → (int) f long → (int)(f ^ (f >>> 32)) float → Float.floatToIntBits(f) double → Double.doubleToLongBits(f) then treat as long
Object → recursive hashCode() or 0 if null Array → use java.util.Arrays.hashCode on each element
Combine each contribution, typically with result = 31 * result + fieldHash;.
Summary
equalsdetermines logical equality of objects, while hashCode provides a fast way to locate objects in hash‑based data structures. Overriding both correctly ensures that collections such as HashMap and HashSet work efficiently and without logical errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
