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.
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.
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 ); } }
home |
Canadian Mind Products | |||
| 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 | |||