hashCode() and equals() work together to help Java collections identify, store, and retrieve objects efficiently. The hashCode() method determines where an object should be stored, while equals() verifies whether two objects are actually equal. This collaboration is especially important in hash-based collections such as HashSet, HashMap, and Hashtable.
Key Points: • hashCode() helps locate the correct bucket for an object. • equals() determines whether two objects represent the same logical data. • Both methods are essential for detecting duplicates in hash-based collections. • Incorrect implementation can lead to duplicate entries or failed lookups. • Custom classes should override both methods together.
How hashCode() Works:
The hashCode() method generates an integer value that is used to determine the bucket where an object should be stored.
Example:
String name = "Java";
int hash = name.hashCode();Benefits:
• Faster searching • Efficient storage • Reduced lookup time
How equals() Works:
The equals() method compares the actual content of two objects to determine logical equality.
Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2));Output:
true
How They Work Together:
When an object is added to a HashSet or used as a key in a HashMap:
1. hashCode() determines the bucket location. 2. If the bucket is empty, the object is stored. 3. If another object already exists in that bucket, equals() is called. 4. If equals() returns true, the object is treated as a duplicate. 5. If equals() returns false, both objects are stored in the same bucket.
Example: Suppose we add two Employee objects with the same ID.
Code Example:
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
class Employee {
private int id;
Employee(int id) {
this.id = id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee emp = (Employee) obj;
return this.id == emp.id;
}
}
public class Demo {
public static void main(String[] args) {
Set<Employee> employees =
new HashSet<>();
employees.add(new Employee(101));
employees.add(new Employee(101));
System.out.println(employees.size());
}
}Output:
1
Although two objects were created, HashSet stores only one because hashCode() and equals() identify them as duplicates.
What Happens If Only equals() Is Overridden?
Problems may occur because objects can be placed in different buckets.
Result:
• Duplicate objects may appear in HashSet. • HashMap lookups may fail.
What Happens If Only hashCode() Is Overridden?
Objects may end up in the same bucket, but equality checks may fail.
Result:
• Duplicate entries may still be stored. • Collection behavior becomes inconsistent.
Contract Between hashCode() and equals():
• If two objects are equal according to equals(), they must return the same hashCode(). • If two objects have the same hashCode(), they are not necessarily equal. • Unequal objects can have different or identical hash codes.
Real-World Example:
Consider a HashSet storing employee records.
Employee(101, "John")
Employee(101, "John")If hashCode() and equals() are implemented correctly:
• Only one employee record is stored. • Duplicate data is prevented.
Interview Tip: A concise interview answer is:
"hashCode() and equals() work together in hash-based collections. hashCode() determines the bucket where an object is stored, while equals() checks whether two objects are logically equal. Hash-based collections use both methods to identify duplicates, perform lookups efficiently, and maintain data integrity."