结合原始类型和泛型方法 [英] Combining Raw Types and Generic Methods
问题描述
这里有一个问题,第一个代码清单编译得很好(JDK 1.6 | JDK 1.7):
Here's a question, this first code listing compiles just fine (JDK 1.6 | JDK 1.7):
ArrayList<String> a = new ArrayList<String>();
String[] s = a.toArray(new String[0]);
但是,如果我将 List
引用声明为原始类型:
However, if I declare the List
reference as a raw type:
ArrayList a = new ArrayList();
String[] s = a.toArray(new String[0]);
我收到一个编译器错误,提示 String[]
是必需的,但找到了 Object[]
.
I get a compiler error saying the String[]
is required but Object[]
was found.
这意味着我的编译器将通用方法解释为返回 Object[]
,尽管接收到 String[]
作为其参数.
This means my compiler is interpreting the generic method as returning Object[]
despite of receiving a String[]
as its argument.
我仔细检查了 toArray(myArray)
方法签名:
I doubled-checked the toArray(myArray)
method signature:
<T> T[] toArray(T[] a);
因此它是一个参数化方法,其类型参数
与List的类型参数(即
)没有任何关系.
Therefore it is a parameterized method whose type parameter <T>
has no relation whatsoever with that of the List (i.e. <E>
).
我不知道这里使用原始类型如何影响使用独立类型参数的参数化方法的评估.
I have no idea how using a raw type here affects the evaluation of parameterized methods using independent type parameters.
- 有谁知道为什么这段代码不能编译?
- 有人知道记录此行为的任何参考资料吗?
推荐答案
这不是您所期望的,但是如果您以原始形式引用泛型类,您将失去在任何情况下使用泛型的能力方式例如成员.它也不限于泛型方法,请查看:
It's not exactly what you'd expect, but if you refer to a generic class in raw form, you lose the ability to use generics in any way for instance members. It's not restricted to generic methods either, check out this:
public class MyContainer<T> {
public List<String> strings() {
return Arrays.asList("a", "b");
}
}
MyContainer container = new MyContainer<Integer>();
List<String> strings = container.strings(); //gives unchecked warning!
这是 JLS 的相关部分(4.8):
This is the relevant part of the JLS (4.8):
未从其超类或超接口继承的原始类型 C 的构造函数(第 8.8 节)、实例方法(第 8.4 节、第 9.4 节)或非静态字段(第 8.3 节)的类型 M 是原始类型对应于在 C 对应的泛型声明中擦除其类型的类型.
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.
这篇关于结合原始类型和泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!