Java Reference
In-Depth Information
Display 14.9
Using a Generic Class with Two Type Parameters (part 2 of 2)
15
System.out.println(
16
"Our new rating for " + rating.getFirst());
17
System.out.println(" is " + rating.getSecond());
18
}
19
}
Sample Dialogue
Our current rating for The Car Guys
is 8
How would you rate them?
10
Our new rating for The Car Guys
is 10
Bounds for Type Parameters
Sometimes it does not make sense to plug in just any reference type for the type
parameter in a generic class definition. For example, consider the generic class Pair
defined in Display 14.5. Suppose we want to add a method that returns the maximum
of the two elements in an ordered pair. We could add the following method definition
to the class Pair in Display 14.5:
max
public T max()
{
if (first.compareTo(second) <= 0)
return first;
else
return second;
}
Recall that the method compareTo is required to be a member of any class that
implements the Comparable interface. The Comparable interface is a standard Java
interface that was discussed in Chapter 13. As a reminder, recall that the Comparable
interface has only the following method heading that must be implemented:
compareTo
public int compareTo(Object other);
When defining a class that implements the Comparable interface, the programmer is
expected to define compareTo so that it returns
a negative number if the calling object “comes before” the parameter other ,
a zero if the calling object “equals” the parameter other ,
and a positive number if the calling object “comes after” the parameter other .
 
Search WWH ::




Custom Search