• 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 & hashcode vs comparable ?

 
Ranch Hand
Posts: 220
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am a little confuse about when to use equals & hashcode for object equality or using comparable interface ?
Isn't it enough to override only equals and hashcode for equality ?

Can anybody give me example ?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Simply, it depends on the collection that you are using. If you are using a Hashtable, HashMap, HashSet, etc., ie. any hashing collection, you will need to override equals() and hashCode() for your object to be stored properly.

If you are using a TreeSet, or any collection that sorts the elements, then you either need to implement Comparable, or use a Comparator.

And if you don't know how your class will be used, but can be used in any of the collection classes, by other developers, then I guess, you should implement both.

Henry
 
Tuna Töre
Ranch Hand
Posts: 220
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Henry thanks for your response,

I think i got the idea ...

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic