Java Reference
In-Depth Information
1
package weiss.util;
2
3
/**
4
* Comparator function object interface.
5
*/
6
public interface Comparator<AnyType>
7
{
8
/**
9
* Return the result of comparing lhs and rhs.
10
* @param lhs first object.
11
* @param rhs second object.
12
* @return < 0 if lhs is less than rhs,
13
* 0 if lhs is equal to rhs,
14
* > 0 if lhs is greater than rhs.
15
*/
16
int compare( AnyType lhs, AnyType rhs );
17
}
figure 4.39
The
Comparator
interface, originally
defined in
java.util
and rewritten for the
weiss.util
package
Using this interface, we can now pass a
Comparator
as the second
parameter to
findMax
. If this
Comparator
is
cmp
, we can safely make the call
cmp.compare(o1,o2)
to compare any two objects as needed. A wildcard used
in the
Comparator
parameter to indicate that the
Comparator
knows how to
compare objects that are the same type or supertypes of those in the array.
It is up to the caller of
findMax
to pass an appropriately implemented
instance of
Comparator
as the actual argument.
An example is shown in Figure 4.40.
findMax
now takes two parameters.
The second parameter is the function object. As shown on line 11,
findMax
expects that the function object implements a method named
compare
, and it
must do so, since it implements the
Comparator
interface.
Once
findMax
is written, it can be called in
main
. To do so, we need to
pass to
findMax
an array of
SimpleRectangle
objects and a function object that
implements the
Comparator
interface. We implement
OrderRectByWidth
, a new
class that contains the required
compare
method. The
compare
method returns
an integer indicating if the first rectangle is less than, equal to, or greater than
the second rectangle on the basis of widths.
main
simply passes an instance
of
OrderRectByWidth
to
findMax
.
7
Both
main
and
OrderRectByWidth
are shown in
7. The trick of implementing
compare
by subtracting works for
int
s as long as both are the same
sign. Otherwise, there is a possibility of overflow. This simplifying trick is also why we use
SimpleRectangle,
rather than
Rectangle
(which stored widths as
doubles
)
.
Search WWH ::
Custom Search