Next page | Contents page |

Comparing objects for sorting

java.lang.Comparable<T>

To be able to do a binary search or sort a collection of data, the objects must have an ordering. To ensure a natural ordering:

	class X implements Comparable<T> 

ensures X has the method int compareTo (T other) which returns <0, 0, or >0 (this object precedes, equals or follows other).

java.lang.String does implement Comparable<String>

compareTo () must be written such that

  1. (x.compareTo (y) > 0 && y.compareTo (z) > 0) => x.compareTo (z) > 0 (transitivity)
  2. x.compareTo(y) == 0 => sign (x.compareTo(z)) == sign (y.compareTo(z)), for all z
  3. (x.compareTo (y) == 0) <=> (x.equals (y))

java.util.Comparator<T>

This interface is for when you want to sort objects in different ways on different occasions (eg, customers sorted by name or order number). Implement this interface in order to construct Comparator objects for passing into search/sort methods.

Two methods in the interface:

	int compare (T obj1, T obj2) 
	boolean equals (Object obj) 

NB: The latter is for testing whether two Comparators are equal.

Library implementations are java.text.Collator and its subclass java.text.RuleBasedCollator which are useful in localisation.

Next page | Contents page |