Understanding the use of Generics in a java collection class

Having studied the Java Collection class (OpenJDK 8_update40), I found the following method:

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;
}

I do not quite understand the use of generic types here. As I understand it, T is a subtype of Object, which should also implement the Comparable interface, which is also parameterized through a common parameter. The parameter of Comparable states, which must be some kind of supertype T. In this regard, we have some kind of definition of a recursive type.

But here is my question: as far as I know, each type of Java is a subtype of Object, so why do they indicate it in the definition of T?

+4
source share
3 answers

.

, , :

<T extends Foo & Bar> void someMethod(T xxx)

someMethod :

void someMethod(Foo xxx)

(, , , ).

Collections.max() JDK 5; :

public static Object max(Collection coll)

Java 5 :

public static Object max(Collection<Object> coll)

, max Comparable...


, :

  • ;
  • Comparable "" PECS (, Comparable<? super T>);
  • Collection, , , T, -, T, ? extends T; , Collection -, T.

...

+6

, "T", Object.

, String Object, , Object.

0

.

:

  • T, <? extends T>, Iterator
  • T, <? super T>, Comparable
0

Source: https://habr.com/ru/post/1607826/


All Articles