FAQ
1. Is it mandatory to override equals
and hashCode
?
equals
and hashCode
?No, it is not mandatory to override equals()
and hashCode()
, but it is recommended when working with custom objects that will be used in collections like HashSet
, HashMap
, or HashTable
.
By default, equals()
and hashCode()
are inherited from Object
:
equals()
compares object references (not values).hashCode()
returns a unique integer for the object instance.
If you don't override them, two objects with the same data may be considered different in collections.
2. What if I just implement equals()
and not hashCode()
?
equals()
and not hashCode()
?If you override equals()
but do not override hashCode()
, our object may behave unexpectedly in hash-based collections.
Example:
Why?
equals()
considerse1
ande2
equal.But since
hashCode()
is not overridden,e1
ande2
may have different hash codes, soHashSet
treats them as different objects.
3. What if I implement hashCode()
but not equals()
?
hashCode()
but not equals()
?If we override hashCode()
but not equals()
, two objects may have the same hash code but still be considered not equal.
Example:
Why?
Even though
hashCode()
returns the same value,equals()
still checks object references, which are different.This can cause incorrect behavior in
HashMap
,HashSet
, etc.
4. Can two objects have the same hash code but not be equal?
Yes, this is called a hash collision.
Example:
Why?
Since we forcefully return
100
for all objects, different objects have the samehashCode
.But
equals()
differentiates them correctly.
5. Can two objects be equal but have different hash codes?
No, if two objects are equal, they must have the same hash code.
According to the contract of hashCode()
and equals()
:
If
a.equals(b) == true
, thena.hashCode() == b.hashCode()
must also be true.
Example (Incorrect implementation breaking contract):
Why is this incorrect?
Since
equals()
says two cars with the same model are equal, theirhashCode()
must also be the same.But due to random hash generation, they have different hash codes, which violates the contract.
Last updated
Was this helpful?