Java Reference
In-Depth Information
1
import java.util.Comparator;
2
3
class CompareTestInner1
4
{
5
private static class OrderRectByWidth implements Comparator<SimpleRectangle>
6
{
7
public int compare( SimpleRectangle r1, SimpleRectangle r2 )
8
{ return r1.getWidth( ) - r2.getWidth( ); }
9
}
10
11
public static void main( String [ ] args )
12
{
13
SimpleRectangle [ ] rects = new SimpleRectangle[ 4 ];
14
rects[ 0 ] = new SimpleRectangle( 1, 10 );
15
rects[ 1 ] = new SimpleRectangle( 20, 1 );
16
rects[ 2 ] = new SimpleRectangle( 4, 6 );
17
rects[ 3 ] = new SimpleRectangle( 5, 5 );
18
19
System.out.println( "MAX WIDTH: " +
20
Utils.findMax( rects, new OrderRectByWidth( ) ) );
21
}
22
}
figure 4.42
Using a nested class to hide the
OrderRectByWidth
class declaration
1
class CompareTestInner2
2
{
3
public static void main( String [ ] args )
4
{
5
SimpleRectangle [ ] rects = new SimpleRectangle[ 4 ];
6
rects[ 0 ] = new SimpleRectangle( 1, 10 );
7
rects[ 1 ] = new SimpleRectangle( 20, 1 );
8
rects[ 2 ] = new SimpleRectangle( 4, 6 );
9
rects[ 3 ] = new SimpleRectangle( 5, 5 );
10
11
class OrderRectByWidth implements Comparator<SimpleRectangle>
12
{
13
public int compare( SimpleRectangle r1, SimpleRectangle r2 )
14
{ return r1.getWidth( ) - r2.getWidth( ); }
15
}
16
17
System.out.println( "MAX WIDTH: " +
18
Utils.findMax( rects, new OrderRectByWidth( ) ) );
19
}
20
}
figure 4.43
Using a local class to hide the
OrderRectByWidth
class declaration further
Search WWH ::
Custom Search