File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashcode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashcode" Watch "hashcode" New topic


Santhi Bharath
Ranch Hand

Joined: Jun 03, 2008
Posts: 75
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??

thanks and regards<br />Santhi Bharath<br />SCJP 5.0, SCWCD 5.0
Himanshu Gupta
Ranch Hand

Joined: Aug 18, 2008
Posts: 598

It depends on the requirements. Mostly when we use collections to hold objects we make use of overriding hashCode() and equals().

My Blog SCJP 5 SCWCD 5
Manju Kavi
Ranch Hand

Joined: Sep 25, 2008
Posts: 33
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

Joined: Oct 09, 2007
Posts: 206

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.

Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Marco Piva

Joined: Aug 24, 2007
Posts: 12
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 ]

SCJP 5.0
Santhi Bharath
Ranch Hand

Joined: Jun 03, 2008
Posts: 75
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

Joined: Sep 26, 2008
Posts: 9
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.
I agree. Here's the link:
subject: hashcode
It's not a secret anymore!