![]() |
VOOZH | about |
In Java, hash-based collections such as HashMap, HashSet, and Hashtable use the hashCode() method to decide the bucket where an object is stored. After locating the bucket, the equals() method is used to compare objects.
Hence, to ensure correct behavior in hash-based collections, both methods must be overridden together and consistently.
As stated by Joshua Bloch (Effective Java): You must override hashCode() in every class that overrides equals().
According to java.lang.Object contract:
When both methods are overridden properly, hash-based collections work as expected, and duplicate keys are avoided.
Example: This program shows why overriding both equals() and hashCode() is necessary when using objects as HashMap keys.
IT
Explanation:
Here, equals() is overridden but hashCode() is not. This causes Java to place objects in different buckets.
Example: This program shows what happens when only equals() is overridden and hashCode() is not.
IT CSE
Explanation:
Here, hashCode() is overridden but equals() is not. Java compares objects using memory reference, not data.
Example: This program shows what happens when only hashCode() is overridden and equals() is not.
CSE IT
Explanation: