“Does it makes sense to compare two Oranges? If so they are Comparable. I will need a method that compares this Orange Object to (compareTo) another. If I want do define an alternate order, I need to invent some sort of independent machine, a Comparator to do it. The comparison is not inherent to Oranges, so there is no this. Instead, I compare two Orange Objects.”
public final int compare( Object o1, Object o2 ); public boolean equals( Object obj );Here is a typical java.util.Comparator.compare routine: If you are using a java.util.Comparator only once, you might implement it as an anonymous inner class like this: Here is a very general purpose Comparator for sorting rows of a Table (array of arrays or Vector of arrays) where each element is some sort of Object that implements Comparable.
String.CASE_INSENSITIVE_ORDER is a Comparator you can use without writing any code. Unfortunately there is no String.CASE_SENSITIVE_ORDER. The reason is String’s Comparable implementation provides it naturally without a Comparator. You can use the following code to sort by natural Comparable order when a Comparator is required.
You can use Collections. reverseOrder() to generate a Comparator that sorts in revese order to the usual Comparable. You can use Collections. reverseOrder( Comparable t ) to generate a Comparator that sorts in reverse order to a given Comparator. If you have a Comparable, you could roll your own Comparator that sorts in descending order like this:Beware of using subtraction in writing Comparators 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.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.16] | ![]() | ||
| You are visitor number 57,172. | |||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/Mindprod website mirror) | ||
| http://mindprod.com/jgloss/comparator.html | J:\mindprod\jgloss\comparator.html | ||