• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

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.
 
I will suppress my every urge. But not this shameless plug:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic