简体   繁体   中英

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

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM