• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator and Compareable

 
Amirr Rafique
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

What is difference in Comparator and Compareable interface. Please also explain following line
"Objects can specify thier natural order by implementing the Compareable interface, or be dictated a total order by comparator which implements the Comparator interface."

Any one can please explain with example

Thanks
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Comparable interface imposes a total ordering on the objects of the class that implements it. This is done using the compareTo method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).

Comparator can be passed to a sort method (such as Collections.sort) to allow control over the sort order and give you the capability to sort a given collection any number of different ways. A comparator class is solely built often to serve a a sorting aid to OTHER classes based on the criterion defined.

Look at the DVD example in K&S Pg.554. where the DVDInfo implements comparable to sort dvds based on title, and then a comparator class is defined, an object of which is passed to the Collections.sort method to sort based on genre.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you can check this thread.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you follow the links within the link wise owen provided above, you'll find a note on what helped me with the distinction:
  • "Comparable" is an adjective. So if an object is Comparable, that means it can be compared to other objects. Note that the method compareTo(Object o1) takes a single argument -- a reference to the object that the Comparator ("this") is being compared to.
  • "Comparator" is a noun. Specifically, it is an object used to compare other objects. Note that the method compare(Object o1, Object o2) takes two arguments -- ordered references to the objects being compared to each other.
  •  
    Sharn Arora
    Ranch Hand
    Posts: 57
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Are Comparator and Compareable interfaces part of Java 1.4 objectives?
    Would really appreciate an answer to this ques. Thanks.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic