简体   繁体   English

如果不同的Java泛型类型参数具有相同的名称,为什么可以为其分配不同的类型?

[英]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: 在oracle的官方java文档Type Inference章节中,有一个这样的例子:

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? 在这种情况下,类型参数是T但是传递了两种不同的类型,不应该a1的类型与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 . 对于您的示例,最具体的类型是Serializable ,它是StringArrayList祖先。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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