Java Reference
In-Depth Information
figure 4.40
The generic findMax
algorithm, using a
function object
1 public class Utils
2 {
3 // Generic findMax with a function object.
4 // Precondition: a.length > 0.
5 public static <AnyType> AnyType
6 findMax( AnyType [ ] a, Comparator<? super AnyType> cmp )
7 {
8 int maxIndex = 0;
9
10 for( int i = 1; i < a.length; i++ )
11 if( cmp.compare( a[ i ], a[ maxIndex ] ) > 0 )
12 maxIndex = i;
13
14 return a[ maxIndex ];
15 }
16 }
Figure 4.41. Observe that the OrderRectByWidth object has no data members.
This is usually true of function objects.
The function object technique is an illustration of a pattern that we see
over and over again, not just in Java, but in any language that has objects. In
Java, this pattern is used over and over and over again and represents perhaps
the single dominant idiomatic use of interfaces.
figure 4.41
An example of a
function object
1 class OrderRectByWidth implements Comparator<SimpleRectangle>
2 {
3 public int compare( SimpleRectangle r1, SimpleRectangle r2 )
4 { return( r1.getWidth() - r2.getWidth() ); }
5 }
6
7 public class CompareTest
8 {
9 public static void main( String [ ] args )
10 {
11 SimpleRectangle [ ] rects = new SimpleRectangle[ 4 ];
12 rects[ 0 ] = new SimpleRectangle( 1, 10 );
13 rects[ 1 ] = new SimpleRectangle( 20, 1 );
14 rects[ 2 ] = new SimpleRectangle( 4, 6 );
15 rects[ 3 ] = new SimpleRectangle( 5, 5 );
16
17 System.out.println( "MAX WIDTH: " +
18 Utils.findMax( rects, new OrderRectByWidth( ) ) );
19 }
20 }
 
Search WWH ::




Custom Search