aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparable, Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparable, Comparator" Watch "Comparable, Comparator" New topic
Author

Comparable, Comparator

Chris Cairns
Ranch Hand

Joined: Jan 31, 2003
Posts: 48
Please, explain the difference!
Reid M. Pinchback
Ranch Hand

Joined: Jan 25, 2002
Posts: 775
Let's say you have a class called Weight, and you want to compare objects of that class (e.g. for sorting).
You have two choices.
1. Weight can implement Comparable.
This means that the Weight class has some default ordering scheme that will be used by any code that cares about ordering (e.g. java.util collections).
2. Some class, not necessarily Weight, can implement Comparator.
This means that you may have many ways of ordering Weights. For example, you can have an IncreasingWeightOrder, DecreasingWeightOrder, etc. You pass objects that implement the interface in various ways to get the effect you want. If you don't pass one of those objects, then the comparator has no impact on anything.


Reid - SCJP2 (April 2002)
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
http://www.javaranch.com/newsletter/July2002/newsletterjuly2002.jsp#collections
Scroll down to the "Sorting Collections" section.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Comparable, Comparator