This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hashcode and Equals Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Hashcode and Equals" Watch "Hashcode and Equals" New topic
Author

Hashcode and Equals

harmeet saini
Ranch Hand

Joined: Apr 11, 2010
Posts: 33
Hi
I am very much confused regarding this " if equals is overridden should hashCode also be overridden"

I am confused coz in CertPal i found two explanations

1) Nothing can prevent a progremmer for not overriding hashCode when overiding equals

2) if equals is overridden should hashCode also be overridden


Regards,
Harmeet Singh
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

http://www.javaworld.com/community/?q=node/1006
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

harmeet saini wrote:Hi
I am very much confused regarding this " if equals is overridden should hashCode also be overridden"

I am confused coz in CertPal i found two explanations

1) Nothing can prevent a progremmer for not overriding hashCode when overiding equals

2) if equals is overridden should hashCode also be overridden


This is a conract, not a must. It doesn't create any syntatic problem wen compiling, but you'll get some logical problems, if you don't override for your own purposes. Check the equal/hashCode contracts.


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6588
    
    1

Nothing can prevent a progremmer for not overriding hashCode when overiding equals

This is a contract, not a must.


Yep. You will not get compile time errors, but you will encounter problems when you put your custom classes into collections that rely on hashing

SCJP 6 articles - SCJP 5/6 mock exams - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hashcode and Equals
 
Similar Threads
Necessity to override both equals() and override() methods
Overriding equals()
Reg Hashcodes
How to over ride the List.contains() method.
why hashcode same for String not for Class Object?