• Post Reply Bookmark Topic Watch Topic
  • New Topic

when should we use comparable, comparator, equals, hash code  RSS feed

 
raj talatam
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

if i want compare objects in collection when should i have to override equals and hash code methods and when should i use comparable and comparator interfaces

thnkas
rajendar
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to just store your objects in a set/map (which is not sorted) use equals/hashCode.
If you want to store your objects sorted set/map and provide natural sorting for them use Comparable.
If you want to store your objects sorted in a way other that natural order use Comparator.
 
Claude Moore
Ranch Hand
Posts: 924
9
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

you need to implement equals to define an equality criterion to apply to instances of the same class; hashCode is needed when you have to deal with Maps (or other structures that uses hashcode to distribute items in buckets)
for performance reasons.

When implementing Comparable, you are providing your class with a method that establishes an ordering criterion; of course this should be consistent with your equals() implementation.

With comparator, you can explicity override ordering criterion for a List, overriding default ordering as well as the ordering specified with compareTo method.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!