• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

equals and hashcode foa an Onject

 
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,

Can anyone please tell me where exactly overriding equals and hashcode will be useful in a Application ??
 
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you .That was a nice explanation .
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
no problem
 
reply
    Bookmark Topic Watch Topic
  • New Topic