Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If different Java generic type parameter have the same name, why it can be assigned different types?

Tags:

java

generics

In oracle's official java document, Type Inference chapter, there's an example like this:

static <T> T pick(T a1, T a2) { return a2; }  
Serializable s = pick("d", new ArrayList<String>());

In this case the type parameters are T but was passed two different type, shouldn't a1's type be the same as a2?

like image 901
woodybird Avatar asked Jan 17 '26 05:01

woodybird


1 Answers

The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

And the most specific type for your example is Serializable, which is ancestor to both String and ArrayList.

like image 186
xiaofeng.li Avatar answered Jan 19 '26 19:01

xiaofeng.li



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!