Comparable : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

Comparable

java.lang.Comparable is used to define the natural sort order of a class. In contrast, java.lang.Comparator is used to define an auxiliary sort order for a class.

Normally you also redefine equals when you implement Comparable even though it is not part of the Comparable interface. There are no generics involved in overriding equals.

To implement Comparable you must write only one method: compareTo. It is typically added to an existing class to describe the natural order of that class. compareTo compares this object with another.

public int compareTo( Object o );
Beware of using subtraction in writing Comparables rather than < > if there is any possibility you will be using numbers large enough to overflow and give the wrong sign comparing them with subtraction. This rarely happens in practice, but when it does it can be baffling.

Comparable Using Generics

Comparable Gotcha

If
// base class
class SalesTaxItem implements Comparable<SalesTaxItem>
{
...
}

and you try to extend it with:

you will get this error message. Comparable cannot be inherited with different arguments

The best way I know of to bypass the problem is to write both classes without the implements Comparable. Then write two Comparators instead.

Descending/Inverse/Reverse Order with reverseOrder

Sorting ascending order means sorting with the small elements first then the big. This is usual ordering. Descending order means sorting with the big elements first then the small.

If you have a Comparator or Comparable of some kind, you can convert it into one that sorts into the reverse of the usual order, e. g. if the original sorts alphabetically, the new one will sort in reverse alphabetical order. Here is how you use it:

If you don’t have a suitable base Comparator, just write an ordinary Comparator from scratch and reverse the operands to each compare inside it, or return - result instead of result.

Learning More

Oracle’s Javadoc on Comparable class : available:
Note java.lang.Comparable but java. util.Comparator.
Oracle’s Javadoc on Comparator class : available:
Oracle’s Javadoc on Collections.reverseOrder() : available:
Oracle’s Javadoc on Collections.reverseOrder(Comparator) : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/comparable.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\comparable.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[54.162.124.193]
You are visitor number