I am tryng to understand how generics works in Java. The following code is from Collections.max()
method of OpenJDK.
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
<T extends Object & Comparable<? super T>>
- The method expects
T
to be a subclass ofObject
and it should implementComparable
interface in order to compare the elements of the collection. - (a) a collection always stores typed objects, which are anyways sub-types of
Object
. IsT extends Object
redundant in this case ? - (b)
Comparable<T>
is not enough ? why do we needComparable<? super T>
?
- The method expects
max(Collection<? extends T> coll)
- (c) Again my doubt here is that, why is
Collection<? extends T>
needed ? Can it beCollection<T>
?
- (c) Again my doubt here is that, why is