0

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 of Object and it should implement Comparable interface in order to compare the elements of the collection.
    • (a) a collection always stores typed objects, which are anyways sub-types of Object. Is T extends Object redundant in this case ?
    • (b) Comparable<T> is not enough ? why do we need Comparable<? super T> ?
  • max(Collection<? extends T> coll)

    • (c) Again my doubt here is that, why is Collection<? extends T> needed ? Can it be Collection<T> ?
ryandam
  • 684
  • 5
  • 13
  • @Clyky, the part about `` is a duplicate of the question you linked and https://stackoverflow.com/a/19488411/814206 gives a good answer. That leaves the part "why do we need `Comparable super T>` and `Collection extends T>`", perhaps OP can edit the question. There might exist a duplicate for the latter part as well. – Kasper van den Berg Jul 08 '18 at 09:05
  • The "Why do we need ``" part is a possible duplicate of https://stackoverflow.com/q/25779184/814206. – Kasper van den Berg Jul 08 '18 at 09:09

0 Answers0