0

I have read in a book that

"The value received from hashcode() is used as bucket number for storing elements."

My doubt is if the bucket contains more than one elements(with same hashcode value),How can differentiate the elements ?

OR

Is it possible more than one elemets has same hashcode ?

Anptk
  • 1,125
  • 2
  • 17
  • 28
  • 2
    Buckets can contain more than one element. The container will use `equals()` to check if each of them is the thing you are looking for. – khelwood Feb 13 '15 at 07:24

3 Answers3

2

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Multiple elements can have the same hashcode. In this case all the elements in that bucket will be checked using the equals() method to determine if one of them matches the one you are looking for.

Relevart
  • 737
  • 1
  • 7
  • 20
0

It is possible to have more than one element with same hashcode cause count of hashcode is limited set. And you can differentiate the elements via equals() method.

Milkmaid
  • 1,659
  • 4
  • 26
  • 39