Java Reference
In-Depth Information
39
/**
40
* Returns the maximum object in the collection,
41
* using default ordering
42
* @param coll the collection.
43
* @return the maximum object.
44
* @throws NoSuchElementException if coll is empty.
45
* @throws ClassCastException if objects in collection
46
* cannot be compared.
47
*/
48
public static <AnyType extends Object & Comparable<? super AnyType>>
49
AnyType max( Collection<? extends AnyType> coll )
50
{
51
return max( coll, new DefaultComparator<AnyType>( ) );
52
}
53
54
/**
55
* Returns the maximum object in the collection.
56
* @param coll the collection.
57
* @param cmp the comparator.
58
* @return the maximum object.
59
* @throws NoSuchElementException if coll is empty.
60
* @throws ClassCastException if objects in collection
61
* cannot be compared.
62
*/
63
public static <AnyType>
64
AnyType max( Collection<? extends AnyType> coll, Comparator<? super AnyType> cmp )
65
{
66
if( coll.size( ) == 0 )
67
throw new NoSuchElementException( );
68
69
Iterator<? extends AnyType> itr = coll.iterator( );
70
AnyType maxValue = itr.next( );
71
72
while( itr.hasNext( ) )
73
{
74
AnyType current = itr.next( );
75
if( cmp.compare( current, maxValue ) > 0 )
76
maxValue = current;
77
}
78
79
return maxValue;
80
}
81
}
figure 6.14
The
Collections
class (part 2):
max
by supplying the default comparator. The funky syntax in the type param-
eter list is used to ensure that the type erasure of
max
generates
Object
(rather than
Comparable
). This is important because earlier versions of Java
Search WWH ::
Custom Search