• Post Reply Bookmark Topic Watch Topic
  • New Topic

comparable vs comparator interface  RSS feed

 
sage erosenin
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help understand when to implement / use the comparable interface against comparator
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically you should implement the Comparable interface when you want objects of a class to be sortable by one specific order or there is some natural sort order for a class (like the natural sort order of numbers). If you need multiple ways to compare/sort objects of a class like sort by id, by firstname, by lastname etc., then the Comparator interface allows you to implement multiple comparators which you can use to sort objects with different sort criteria.

Marco
 
Kaushik Baral
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you have details of few Employees. details are Name, age, designation.
if you want to sort the employees every time by their name then use comparable class.
but if you want to sort the employee details in different ways may be some time with the name, some time with designation then you have to use comparator class.
 
sage erosenin
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, makes sense.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!