Java Glossary : Comparator

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : C words : Comparator.

Comparator
java.util.Comparator is used to define a special sort order for a class. In contrast java.lang.Comparable is used to define the natural sort order of a class. To implement java.util.Comparator you must write two methods. It typically describes a small delegate object passed to a sort to describe some special sort order. The compare method compares two objects of the class you want to sort. The equal method compares this java.util.Comparator to another to see if they represent the same order. It does not compare two objects of the class you want to sort.

public final int compare (Object o1, Object o2);
public boolean equals (Object obj);

Here is a typical java.util.Comparator.compare routine:


view

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.


view

String.CASE_INSENSITIVE_ORDER is a Comparator you can use without writing any code. Unforntunately 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.

public class Natural implements Comparator
   {

   /**
   * Compare two objects by their natural orders
   *
   * @param a first object to be compared
   *
   * @param b second object to be compared
   *
   * @return +1 if a>b, 0 if a=b, -1 if a<b
   */
   public final int compare ( Object a, Object b )
      {
      return( (Comparable )a ).compareTo ( b );
      }
   }


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 6271.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/comparator.html J:\mindprod\jgloss\comparator.html