Java Reference
In-Depth Information
To modify it so that min can find the minimum of any array whose base type
is known to have method compareTo defined on it, we change the base type of
parameter b to the name of the interface, Comparable , and change the less-than
relation within the body of the method to a call to method compareTo , as shown
in Fig. 12.4. Here, you can see interface Comparable being used as a class-type,
in that the interface name is used as the type of a variable.
Get Compar-
able and class-
es that use it
from lesson
page 12.3.
Implementing interface Comparable
Figure 12.5 contains class Pixel , each instance of which represents a pixel
in a window. It has a pair (x,y) of coordinates. Only a constructor and method
compareTo are shown, but there may be other methods. We note three things
about class Pixel .
1. Pixel implements Comparable , as shown in the first line of the class.
2. Parameter ob of method compareTo has type Object , as required by
interface Comparable .
3. Each time parameter ob is used, it is cast back to Pixel —without this
cast, fields x and y of the parameter could not be referenced. This cast
will cause an exception if ob is not really a Pixel . The specification of
compareTo makes clear that ob must be a Pixel .
It may seem like a lot of extra baggage to implement Comparable in class Pixel
—making the parameter be an Object but then casting back to Pixel . However,
public class Pixel implements Comparable {
private int x = 0; // horizontal coordinate
private int y = 0; // vertical coordinate
/** Constructor: instance with horizontal coordinate xp and vertical coordinate yp */
public Pixel( int xp, int yp)
{ x = xp; y = yp; }
/** = 0 if this Pixel and Pixel ob are the same;
1 if this Pixel precedes Pixel ob in row-major order;
-1 if this Pixel follows Pixel ob in row-major order. */
public int compareTo(Object ob) {
if (y > ((Pixel)ob).y) return -1;
if (y < ((Pixel)ob).y) return 1;
if (x > ((Pixel)ob).x) return -1;
if (x < ((Pixel)ob).x) return 1;
return 0;
Figure 12.5:
Class Pixel
Search WWH ::

Custom Search