Java Reference
In-Depth Information
The
compareTo
method takes a single object argument of type
T
and com-
pares it to the current object (expected to also be of type
T)
, returning
a negative, zero, or positive integer if the current object is less than,
equal to, or greater than the argument, respectively.
natural ordering for points could be their distance from the origin. We
could then make
Point
objects
Comparable
:
class Point implements Comparable<Point> {
/** Origin reference that never changes */
private static final Point ORIGIN = new Point();
private int x, y;
// ... definition of constructors, setters and accessors
public double distance(Point p) {
int xdiff = x - p.x;
int ydiff = y - p.y;
return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
}
public int compareTo(Point p) {
double pDist = p.distance(ORIGIN);
double dist = this.distance(ORIGIN);
if (dist > pDist)
return 1;
else if (dist == pDist)
return 0;
else
return -1;
}
}