• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

comparable vs comparator interface  RSS feed

 
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
 
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
 
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!