• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt in Hashcode()  RSS feed

 
carox kaur
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In khalid Mughal page 511, hashcode() method is given in detail. I have nor understood certain questions:

What will happen if unequal objects will hash to same bucket ? (page 513)
I know that equal objects should hash to same bucket in the hash table, it enables yielding correct answer on searching that object. But where is the prob if unequal objects will hash to same buckets??? Does it mean that in a bucket only equal objects should be placed???
Assuming ,to deal with hash collision a linked lists is maintained at every array index.
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well unequal objects can land in the same hash bucket. there is no problem in that. The problem arises when equal objects land in different hash buckets. This happens if a class overrides the equals method but not the hashCode method...
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
carox kaur wrote:But where is the prob if unequal objects will hash to same buckets???

The only "problem" is performance. A hash map / set would have to look through more items to find the truly equal object. Other than that, no problem. In fact, it is perfectly legal to return a constant (like 42) as the hash code - but then your hash map / set turns into a linked list instead.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!