Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boundly-extended Wildcards in java Generics

Tags:

java

generics

I was experimenting with Generics for a while and I've come up with smt i cannot explain:

If we have such method that return first element of a collection:

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

And let's say we call it like this:

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

So, my question is What is actual returned type in magic_method ?

<? extends T> 

If we pass Collection of Integer does the compiler automatically "understand" that T should be Number (Since Number is super-class of Integer) ?

Or am i missing something?

like image 689
Anarantt Avatar asked Aug 01 '26 16:08

Anarantt


1 Answers

That's not what extends mean in this context. Here extends means "T or a subtype of T".

Think of ? extends T as a type specifier for something that could be assigned to a variable of type T.

like image 161
aioobe Avatar answered Aug 03 '26 06:08

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!