Limited extended wildcards in java Generics

I've been experimenting with Generics for a while and I came up with smt, I can't explain:

If we have a method like this that returns the first item in the collection:

public static <T> T magic_method(List<? extends T> coll) {
    return coll.get(0);
}

      

And let's say we call it this way:

List<Integer> l = Arrays.asList(12345);
System.out.println(magic_method(l));

      

So my question is What is the return type in magic_method?

<? extends T> 

      

If we go through Collection of Integer

, the compiler will automatically "understand" what it T

should be Number

(Since it Number

is a superclass Integer

)?

Or am I missing something?

+3


source to share


1 answer


This is not what it extends

means in this context. Here extends

means " T

or subtype T

".



Think of it ? extends T

as a type specifier for what can be assigned to a type variable T

.

+2


source







All Articles