• Post Reply Bookmark Topic Watch Topic
  • New Topic

equals and hashcode foa an Onject  RSS feed

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Can anyone please tell me where exactly overriding equals and hashcode will be useful in a Application ??
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Overriding equals and hashcode is useful in the cases when you want to check the equality of objects based on some field of the object.

for ex.
class Book{
int bookId ;
Book(int id){bookId = id;}
}

Book b1 = new Book(1);
Book b2 = new Book(1);

now if you try b1 == b2 you will get false because b1 and b2 refering to two different instances. so if you want to make two instances of book equal in case bookId is equal then you have to override equals.
then b1.equals(b2) will be true. now according to equal contract if two objects are equal then their hashcode must be equal. so if you are overriding equal you should override hashcode as well.
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you .That was a nice explanation .
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no problem
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!