• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Writing efficient hashCode

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is a hashCode method which returns unique value for every object the most efficient one?

If yes, why? As per my understanding, if hashCode returns unique value for every object, then to find the appropriate bucket we have to compare the hashCode with that of every other object and this will give an O(n) time.
 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nope, because the hashCode isn't compared to the bucket. The hashCode is like an address to the bucket. Using the hashCode, the correct bucket can be found in O(1) time.

If each object has a unique hashCode, then objects will be more uniformly distributed over the buckets, and the average time it takes to compare all the objects in the bucket with the one you want to retrieve will be lower.
 
Harsh Pensi
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
 
reply
    Bookmark Topic Watch Topic
  • New Topic