Java Reference
In-Depth Information
The type parameter specifies the type of the objects that this class is willing to
accept for comparison. Usually, this type is the same as the class type itself. For
example, the Coin class would implement Comparable<Coin> , like this:
656
657
public class Coin implements Comparable <Coin>
{
. . .
public int compareTo( Coin other)
{
if (value < other.value) return -1;
if (value == other.value) return 0;
return 1;
}
. . .
}
The type parameter has a significant advantage: You need not use a cast to convert
an Object parameter into the desired type.
A DVANCED T OPIC 14.5: The Comparator Interface
Sometimes, you want so sort an array or array list of objects, but the objects don't
belong to a class that implements the Comparabl e interface. Or, perhaps, you
want to sort the array in a different order. For example, you may want to sort coins
by name rather than by value.
You wouldn't want to change the implementation of a class just in order to call
Arrays.sort . Fortunately, there is an alternative. One version of the
Arrays.sort method does not require that the objects belong to classes that
implement the Comparable interface. Instead, you can supply arbitrary objects.
However, you must also provide a comparator object whose job is to compare
objects. The comparator object must belong to a class that implements the
Comparator interface. That interface has a single method, compare , which
compares two objects.
As of Java version 5.0, the Comparator interface is a parameterized type. The
type parameter specifies the type of the compare parameters. For example,
Comparator<Coin> looks like this:
public interface Comparator<Coin>
Search WWH ::




Custom Search