File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes if we override hashCode method is compulsary to override equals method and viseversa. 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 "if we override hashCode method is compulsary to override equals method and viseversa." Watch "if we override hashCode method is compulsary to override equals method and viseversa." New topic
Author

if we override hashCode method is compulsary to override equals method and viseversa.

varinder mahajan
Ranch Hand

Joined: Jun 11, 2008
Posts: 47
if we override hashCode method is compulsary to override equals method and viseversa.


Beat the world,if you can.......
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

as far as I know if you override the equals method you must override the hashCode method. This is because the hashCode method must return equal hashCodes for objects that are equal according to the equals method. But the default implementation of hashCode method in Object class considers the memory location of the object into calculating hashCode so if you return true from your equals method the hashCode method from the Object class might return unequal hashCodes.

However if you override the hashCode method then you may choose not to implement the equals method. This is because the equals method implementation in the Object class just checks for reference equality. Adding to this hashCode method can return same hashCode for objects that are unequal according to the equals method....

My language is pretty technical but I hope you will get it....Also please correct me if I am wrong.....Thanks...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
varinder mahajan
Ranch Hand

Joined: Jun 11, 2008
Posts: 47
Thanks Ankit , I got it
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: if we override hashCode method is compulsary to override equals method and viseversa.