hashCode() and the equals/hashCode contract
42 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A hash code is an int that an object computes from itself with hashCode(). Equal objects must produce the same hash code, so Java can use the number to find an object fast without checking every object one by one.
What a hash code is for
hashCode() is the Object method that returns an int computed from an object, its hash code. Hash-based collections use it to pick a small group, called a bucket, so they compare an object only with the few objects in that bucket.
A PIN code sends a letter to one small area, so the post office never searches the whole country. A hash code does the same job for objects.
Example 1 · A tiny bucket table
class TinyTable { Object[][] items = new Object[4][5]; int[][] hashes = new int[4][5]; int[] sizes = new int[4];
int bucketOf(int hash) { return Math.abs(hash % 4); }
void add(Object o) { int h = o.hashCode(); int b = bucketOf(h); items[b][sizes[b]] = o; hashes[b][sizes[b]] = h; sizes[b]++; }
boolean contains(Object o) { int h = o.hashCode(); int b = bucketOf(h); for (int i = 0; i < sizes[b]; i++) { if (hashes[b][i] == h && items[b][i].equals(o)) { return true; } } return false; }}
public class BucketDemo { public static void main(String[] args) { TinyTable t = new TinyTable(); String[] names = {"Aarav", "Diya", "Kavya", "Rohan"}; for (int i = 0; i < names.length; i++) { t.add(names[i]); System.out.println(names[i] + " -> bucket " + t.bucketOf(names[i].hashCode())); } System.out.println(t.contains("Kavya")); System.out.println(t.contains("Arjun")); }}Aarav -> bucket 3 Diya -> bucket 1 Kavya -> bucket 0 Rohan -> bucket 0 true false
What this code does
TinyTableis a small model of a hash-based collection: 4 buckets, the bucket number isMath.abs(hashCode() % 4)(%can give a negative remainder, andMath.absmakes it 0 to 3), and it remembers each object's hash code when the object is added.- Kavya and Rohan share bucket 0, so
containsmay meet several objects in one bucket. It compares hash codes first and callsequals()only when they match.
TinyTable is a small model of the hash-based collections, such as HashSet and HashMap, that you will meet in the Collections section. It picks the bucket from hashCode(), then calls equals() only on the few objects inside that bucket, so lookups stay fast even with lakhs of objects.
Default hashCode() and String hashCode()
A hash collision happens when two unequal objects have the same hash code, like "Aa" and "BB" (both 2112). Collisions are allowed and cannot be avoided, because there are far more possible objects than int values; equals() tells them apart.
Object's hashCode() is tied to the object itself, not its data. String overrides it to compute the number from the letters, so equal Strings always share a hash code.
Example 2 · Hash codes of Strings and objects
class Pen {}
public class HashBasicsDemo { public static void main(String[] args) { String a = "Diya"; String b = new String("Diya"); System.out.println(a.hashCode() + " " + b.hashCode()); System.out.println("Aa".hashCode() + " " + "BB".hashCode() + " " + "Aa".equals("BB"));
Pen p1 = new Pen(); Pen p2 = new Pen(); System.out.println(p1.hashCode() == p1.hashCode()); System.out.println(p1.hashCode() == p2.hashCode()); }}2130541 2130541 2112 2112 false true false
What this code does
aandbare different objects but equal Strings, so they have the same hash code, computed from the letters."Aa"and"BB"collide: same hash code, not equal. TwoPenobjects use the default hash code, so they differ.
Two Pen objects with nothing inside still get different numbers, and those numbers can change from one run to the next. Different Strings can share a number, like "Aa" and "BB": that is a collision, and it is normal.
The equals/hashCode contract
The equals/hashCode contract says: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(); hashCode() must return the same value while the fields used by equals() do not change; unequal objects may share a hash code.
A contract here means rules every class must keep, because Java code everywhere relies on them. The pictures show a hash table with 4 buckets: why a collision is harmless, and why equal objects must land in the same bucket.
Read the first rule backwards too: different hash codes mean "surely not equal"; the same hash code means only "maybe equal, check with equals()".
hashCode() while the object sits in a hash-based collection: it would then be searched for in the wrong bucket.Override equals() without hashCode(): what breaks
Say Student overrides equals() but keeps Object's hashCode(). Two equal students now get different hash codes, which breaks the first rule of the contract.
Example 3 · Mistake: equals() without hashCode()
class Student { String name; int roll;
Student(String name, int roll) { this.name = name; this.roll = roll; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Student other = (Student) obj; return roll == other.roll && name.equals(other.name); }}
class TinyTable { Object[][] items = new Object[4][5]; int[][] hashes = new int[4][5]; int[] sizes = new int[4];
int bucketOf(int hash) { return Math.abs(hash % 4); }
void add(Object o) { int h = o.hashCode(); int b = bucketOf(h); items[b][sizes[b]] = o; hashes[b][sizes[b]] = h; sizes[b]++; }
boolean contains(Object o) { int h = o.hashCode(); int b = bucketOf(h); for (int i = 0; i < sizes[b]; i++) { if (hashes[b][i] == h && items[b][i].equals(o)) { return true; } } return false; }}
public class MissingHashDemo { public static void main(String[] args) { Student s1 = new Student("Diya", 7); Student s2 = new Student("Diya", 7); TinyTable t = new TinyTable(); t.add(s1);
System.out.println("equals: " + s1.equals(s2)); System.out.println("same hash: " + (s1.hashCode() == s2.hashCode())); System.out.println("found: " + t.contains(s2)); }}equals: true same hash: false found: false
What this code does
s1ands2are equal, buthashCode()still comes fromObject, so their hash codes differ: the contract is broken.- The table compares hash codes first, so it never even calls
equals()and reports "not found". A realHashSetbehaves the same way.
Nothing crashes and the compiler says nothing: lookups just say "not found" for a student who is there, and duplicates get in. Rule: override equals() and hashCode() together, always.
Writing hashCode() with Objects.hash
Objects.hash(...), from java.util.Objects, combines the hash codes of the values you pass into one int. Pass exactly the fields that equals() compares, so equal objects always get equal hash codes.
Write @Override public int hashCode() and return Objects.hash(...) with exactly the fields equals() compares.
Example 4 · Fix: hashCode() with Objects.hash
import java.util.Objects;
class Student { String name; int roll;
Student(String name, int roll) { this.name = name; this.roll = roll; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Student other = (Student) obj; return roll == other.roll && name.equals(other.name); }
@Override public int hashCode() { return Objects.hash(roll, name); }}
class TinyTable { Object[][] items = new Object[4][5]; int[][] hashes = new int[4][5]; int[] sizes = new int[4];
int bucketOf(int hash) { return Math.abs(hash % 4); }
void add(Object o) { int h = o.hashCode(); int b = bucketOf(h); items[b][sizes[b]] = o; hashes[b][sizes[b]] = h; sizes[b]++; }
boolean contains(Object o) { int h = o.hashCode(); int b = bucketOf(h); for (int i = 0; i < sizes[b]; i++) { if (hashes[b][i] == h && items[b][i].equals(o)) { return true; } } return false; }}
public class HashFixDemo { public static void main(String[] args) { Student s1 = new Student("Diya", 7); Student s2 = new Student("Diya", 7); TinyTable t = new TinyTable(); t.add(s1);
System.out.println(s1.hashCode() + " " + s2.hashCode()); System.out.println("found: " + t.contains(s2)); System.out.println("found Rohan: " + t.contains(new Student("Rohan", 9))); }}2131719 2131719 found: true found Rohan: false
What this code does
Objects.hash(roll, name)uses the same two fields asequals(), so equal students now have equal hash codes.- The table goes to the right bucket and finds Diya; Rohan is correctly "not found".
Example 5 · Mistake: hashCode() uses a field that equals() ignores
import java.util.Objects;
class Book { String isbn; int price;
Book(String isbn, int price) { this.isbn = isbn; this.price = price; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Book other = (Book) obj; return isbn.equals(other.isbn); }
@Override public int hashCode() { return Objects.hash(isbn, price); }}
public class WrongFieldsDemo { public static void main(String[] args) { Book old = new Book("978-81", 299); Book sale = new Book("978-81", 249); System.out.println("equals: " + old.equals(sale)); System.out.println("same hash: " + (old.hashCode() == sale.hashCode())); }}equals: true same hash: false
What this code does
equals()looks only atisbn, buthashCode()also mixes inprice, so two equal books get different hash codes.- Fix:
return Objects.hash(isbn);. Use exactly the fields thatequals()uses.
By hand, the classic form is 31 * roll + name.hashCode(): multiplying by 31 makes the order matter, so (1, 2) and (2, 1) differ. return 0; keeps the contract but puts every object in one bucket, so lookups become as slow as checking a list one by one.
Fix the error
Fix the hashCode() method
Read the error, then pick the line that fixes it.
Round 1 of 3
Point should override hashCode().
Error
Point.java:7: error: method does not override or implement a method from a supertype
@Override
^Next step
Check your understanding
12 quick questions