Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
varinder mahajan
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if we override hashCode method is compulsary to override equals method and viseversa.
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
varinder mahajan
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit , I got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic