• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Comparable and Comparator

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the difference between Comparable and Comparator interfaces?
At what situation these interfaces are used?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look closely at the API documentation for both interfaces.

Interface Comparable<T> has a method: public int compareTo(T o)
Interface Comparator<T> has a method: public int compare(T o1, T o2)

You use Comparable if you want to implement the comparison method into the value object class itself. If you want to keep the comparison method separate from the value object class, you should use Comparator and create a separate class that implements that interface.

Sometimes it's desirable to have the comparison method separate from the value object class itself; for example, if there are different possible orderings, you could write different classes that implement Comparator and choose the one you need at a specific point in the program.
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You may read the Collections 2 Framework tutorial available at http://java.sun.com

It's an excellent introduction to the subject.
 
Your buns are mine! But you can have this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic