The equals() and hashCode() methods are among the most frequently asked topics in Java interviews. They play a critical role in Java Collections Framework, especially when working with HashMap, HashSet and other hash-based collections.
Many developers override one of these methods but forget to override the other, resulting in unexpected bugs and inconsistent behaviour. In this article, we will understand how equals() and hashCode() work, the contract between them, and why both methods are important.
What is equals() Method?
The equals() method is defined in the Object class and is used to compare two objects for equality.
Default implementation:
public boolean equals(Object obj) {
return (this == obj);
}
By default, equals() compares object references, not object contents.
Example Without Overriding equals()
class Employee {
int id;
Employee(int id) {
this.id = id;
}
}
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee(100);
Employee e2 = new Employee(100);
System.out.println(e1.equals(e2));
}
}
Output
false
Even though both employees have the same id, they are different objects in memory.
Overriding equals()
class Employee {
int id;
Employee(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null || getClass() != obj.getClass())
return false;
Employee emp = (Employee)obj;
return this.id == emp.id;
}
}
Output
true
Now the comparison is based on object content rather than memory location.
What is hashCode() Method?
hashCode() returns an integer value that represents the hash code of an object.
Java collections such as HashMap and HashSet use hashCode() to determine where an object should be stored.
String language = "Java";
System.out.println(language.hashCode());
Why Do We Need hashCode()?
Imagine a library with thousands of books. Instead of checking every shelf, books are placed in specific sections based on categories.
Similarly, hashCode() helps Java quickly locate objects inside hash-based collections.
The Contract Between equals() and hashCode()
Java defines an important contract:
- If two objects are equal according to equals(), they must have the same hashCode().
- If two objects have the same hashCode(), they are not necessarily equal.
- If equals() is overridden, hashCode() should also be overridden.
Incorrect Implementation Example
Only equals() is overridden:
class Employee {
int id;
Employee(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
Employee emp = (Employee)obj;
return this.id == emp.id;
}
}
This may cause problems when using HashSet and HashMap.
HashSet Problem Example
Set<Employee> employees =
new HashSet<>();
employees.add(new Employee(1));
employees.add(new Employee(1));
System.out.println(employees.size());
Expected Output
1
Actual Output
2
Because hashCode() was not overridden, Java places both objects into different buckets.
Correct Implementation
class Employee {
int id;
Employee(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null ||
getClass() != obj.getClass())
return false;
Employee emp = (Employee)obj;
return this.id == emp.id;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}
}
Now HashSet correctly treats duplicate employees as identical objects.
How HashMap Uses equals() and hashCode()
HashMap first uses hashCode() to find the bucket.
After locating the bucket, equals() is used to identify the exact object.
Map<Employee, String> map =
new HashMap<>();
Employee e1 = new Employee(1);
map.put(e1, "Java Developer");
Employee e2 = new Employee(1);
System.out.println(map.get(e2));
Without proper equals() and hashCode() implementations, retrieval may fail.
Real Interview Question
Can Two Different Objects Have the Same hashCode()?
Yes. This situation is known as a hash collision.
"Aa".hashCode()
"BB".hashCode()
These strings produce the same hash code but are different objects.
Real Interview Question
Can Equal Objects Have Different hashCodes?
No. Equal objects must always produce the same hashCode().
Violating this rule breaks the contract between equals() and hashCode().
equals() vs == Operator
| equals() | == |
|---|---|
| Compares content | Compares references |
| Can be overridden | Cannot be overridden |
| Works on object state | Works on memory addresses |
Example
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
Output
false
true
Best Practices
- Always override equals() and hashCode() together.
- Use the same fields in both methods.
- Prefer using Objects.hash() for simplicity.
- Test custom objects before storing them in HashMap and HashSet.
Using Objects.hash()
@Override
public int hashCode() {
return Objects.hash(id);
}
This approach is cleaner and easier to maintain.
Common Interview Questions
Why should hashCode() be overridden when equals() is overridden?
Because collections such as HashMap and HashSet depend on hashCode() for bucket selection.
What happens if only equals() is overridden?
Collections may store duplicate objects or fail to retrieve existing objects.
Can two objects have the same hashCode()?
Yes. This is called a hash collision.
Can equal objects have different hashCodes?
No. This violates Java's contract.
Frequently Asked Questions (FAQ)
Which collections rely heavily on equals() and hashCode()?
HashMap, HashSet, Hashtable, LinkedHashMap, and LinkedHashSet.
What is a hash collision?
A hash collision occurs when two different objects generate the same hash code.
Does TreeMap use hashCode()?
No. TreeMap relies on comparison logic and Red-Black Tree structure instead of hashing.
What is the most common mistake with equals() and hashCode()?
Overriding equals() but forgetting to override hashCode().
Conclusion
The equals() and hashCode() methods are fundamental concepts in Java. While equals() determines object equality, hashCode() helps collections efficiently organize and retrieve data. Understanding their relationship is essential for working with HashMap, HashSet, and many other Java collections. Mastering these concepts will help avoid subtle bugs and significantly improve interview performance.
Keywords
equals vs hashCode Java, hashCode Interview Questions, equals Method Java, Java Object Class Methods, HashMap equals hashCode, HashSet equals hashCode, Java Collections Framework, equals vs Double Equals, hashCode Contract Java, Object Equality Java, Java Interview Questions, Hash Collision Java, Overriding equals and hashCode, Core Java Concepts, Java Best Practices
Reviewed by 13thGhost
on
3:07 PM
Rating:

No comments: