Java Reference
In-Depth Information
1 package weiss.util;
2
3 /**
4 * Instanceless class contains static methods that operate on collections.
5 */
6 public class Collections
7 {
8 private Collections( )
9 {
10 }
11
12 /*
13 * Returns a comparator that imposes the reverse of the
14 * default ordering on a collection of objects that
15 * implement the Comparable interface.
16 * @return the comparator.
17 */
18 public static <AnyType> Comparator<AnyType> reverseOrder( )
19 {
20 return new ReverseComparator<AnyType>( );
21 }
22
23 private static class ReverseComparator<AnyType> implements Comparator<AnyType>
24 {
25 public int compare( AnyType lhs, AnyType rhs )
26 {
27 return - ((Comparable)lhs).compareTo( rhs );
28 }
29 }
30
31 static class DefaultComparator<AnyType extends Comparable<? super AnyType>>
32 implements Comparator<AnyType>
33 {
34 public int compare( AnyType lhs, AnyType rhs )
35 {
36 return lhs.compareTo( rhs );
37 }
38 }
figure 6.13
The Collections class (part 1): private constructor and reverseOrder
example of the type of code that might be implemented with an anonymous
class. We have a similar declaration for the default comparator; since the
standard API does not provide a public method to return this, we declare our
method to be package-visible.
Figure 6.14 illustrates the max method, which returns the largest ele-
ment in any Collection . The one-parameter max calls the two-parameter max
Search WWH ::




Custom Search