In general, there are two ways to handle the situation where two or more elements end up in the same "bucket" in a hash table:
A bucket can be a linked list (or equivalent) and hold lots of elements. This is how HashMap
works ... though in Java 8, the linked list can be a binary tree.
A bucket can have a bounded size, and then "overflow" into another one.
My doubt is if the bucket contains more than one elements(with same hashcode value). How can differentiate the elements ?
In Java, the HashMap
, Hashtable
and related classes, use the key's equals
method to differentiate keys with the same hashcode. That's why we have the "hashcode / equals contract". (Read about it here.)
Is it possible more than one elemets has same hashcode?
Yes it is possible. Java's standard hash table classes cope with it. See above.