Java generic method to find 'max' object from collection using compareTo method problem

Mershel :

Lets assume that we have

class A implements Comparable<A>

And

class B extends A

Now, I would like to have generic method that finds biggest object from collection, using compareTo method.

If I declare this method like so:

public static <T extends Comparable<T>> T max(List<T> list)

It won't work for argument List<B> list because B does not parameterize Comparable with type B. For that method to work, it seems natural for me to change

Comparable<T>

To

Comparable<? super T>

So method after that change will look like this:

public static <T extends Comparable<? super T>> T max(List<T> list)

Now passing argument List<B> list works fine and gives no errors. Fine. But when i change method signature to

public static <T extends Comparable<T>> T max(List<? extends T> list)

It also works fine for argument List<B> list! And my question is WHY. Could someone explain that to me? Thanks :)

kumesana :

List<? extends T> means "a List. We don't know a List of what, but whatever it is, we do know that it extends T or is T itself."

One effect of this is that when we take an element from the List, the compiler will know it as of type T. The actual runtime class of the item may be a subtype of T, as is always the case with polymorphism, but no one cares about that. We know it can be stored in a variable type T.

Another effect is that we can't put any element in the List, because we don't know of what the List is. So whatever we'd try to put inside, we don't know if it is of acceptable type, therefore we can't. But when finding the max it doesn't matter: we won't be adding anything anyway.

Therefore, a List<B> can also be taken as a List<? extends A> if needed (suddenly decide that we don't know don't care of what the List is, but whatever it is it extends A.) This is helping because then it allows to match the method signature, taking T as A.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159461&siteId=1
Recommended