Java Reference
In-Depth Information
21.3. Ordering with Comparable and Comparator
The interface java.lang.Comparable<T> can be implemented by any class
whose objects can be sorted. The interface has a single method:
public int compareTo(T other)
Returns a value that is less than, equal to, or greater than zero
as this object is less than, equal to, or greater than the other
object. This method should return zero only if equals with the
same object would return true . If the objects are not mutually
comparable (such as an Integer with a String ), a ClassCastEx-
ception is thrown.
The ordering defined by compareTo is a class's natural ordering, that is,
the ordering that is most natural to objects of the class. It is also a total
ordering, meaning that any two objects of the same type must be mutu-
ally comparablethat is, you must be able to compare them in either order
and always get the same result as to which is the larger. Similarly, the
equals method defines a natural equivalence.
Many existing classes are Comparable , including String , java.io.File ,
java.util.Date , and all the primitive wrapper class types.
If a given class does not implement Comparable or if its natural ordering
is wrong for some purpose, you can often provide a java.util.Comparator
object instead. The Comparator<T> interface has the method
public int compare(T o1, T o2)
Provides
an
ordering
in
the
same
manner
as Compar-
able.compareTo for the two provided objects.
You can use Comparable and Comparator objects to sort and search List ob-
jects with the Collections class's static methods sort and binarySearch .
 
Search WWH ::




Custom Search