Java Reference
In-Depth Information
the objects belong to classes that implement the Comparable interface. That
interface has a single method:
public interface Comparable
{
int compareTo(Object otherObject);
}
654
655
The call
a.compareTo(b)
must return a negative number if a should come before b , 0 if a and b are the same,
and a positive number otherwise.
Several classes in the standard Java library, such as the String and Date classes,
implement the Comparable interface.
You can implement the Comparable interface for your own classes as well. For
example, to sort a collection of coins, the Coi n class would need to implement this
interface and define a compareTo method:
public class Coin implements Comparable
{
. . .
public int compareTo(Object otherObject)
{
Coin other = (Coin) otherObject;
if (value < other.value) return -1;
if (value == other.value) return 0;
return 1;
}
. . .
}
When you implement the compareTo method of the Comparable interface, you
must make sure that the method defines a total ordering relationship, with the
following three properties:
ȗ Antisymmetric: If a.compareTo(b) ʎ 0, then b.compareTo(a) ʏ 0
ȗ Reflexive: a.compareTo(a) = 0
Search WWH ::




Custom Search