• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode

 
Santhi Bharath
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why do we need to override to hashcode when the hashcode() of Object class returning unique value for every object??isn't it enough to override equals() method??
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on the requirements. Mostly when we use collections to hold objects we make use of overriding hashCode() and equals().
 
Manju Kavi
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is used to increase the performance of large collections of data by distributing objects evenly accross the buckets. So there wont be a pain of getting objects accumulated into one single bucket.
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a Contract for equals and Hashcode.

If two objects are equal, then they should have same Hashcode. But if Hashcodes are same, that doesnot mean the Objects are equal.

And also for Efficieny, we need to override Hashcode method.
 
Marco Piva
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The hashCode method defined by class Object does return DISTINCT integers for distinct objects.

If you don't override it you don't satisfy the hashCode contract (because different objects can be equal, and in this case their hashCode() methods should return the same value), and you are not able to locate an object in the hashtable, unless you maintain a reference to the original object.
[ September 26, 2008: Message edited by: M. Piva ]
 
Santhi Bharath
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you overridden equals method then ,
i guess no problem in not overriding the hashcode().because for every object the Object class returning unique hashcode.then we will have single bucket for every object.
 
vipin raimcs
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This depends upon where you want to use it. Just for nomral purpose its sufficient to override the equal method but sometimes its necessary to override the hashcode method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic