“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:
Collections.sort( myArrayList, new Comparator() { public int compare( Object a, Object b ) { return( (String)a ).compareToIgnoreCase( (String) b ); } } );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.
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.
![]() |
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.59] | The information on this page is for non-military use only. | ||
| You are visitor number 61,435. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | ||
| http://mindprod.com/jgloss/comparator.html | J:\mindprod\jgloss\comparator.html | ||