问题描述
private static <T extends Number> ArrayList<T> cast2() {
// This line compiles (1)
return (ArrayList<T>) new ArrayList<Integer>();
}
private static ArrayList<Double> cast3() {
// does not compile (3)
return (ArrayList<Double>) new ArrayList<Integer>();
}
public static void main(String[] argv) {
ArrayList<Double> ld1 = cast2();
// This does not (2)
ArrayList<Double> ld2 = (ArrayList<Double>) new ArrayList<Integer>();
}
很明显,第(2)行和第(3)行不是类型安全的并且不能编译。我对编译的line(1)感到困惑。在函数cast2中将Double替换为T后,与cast3相同,但cast2编译而cast3不相同。
为什么只有ArrayList
解决方法
在函数cast2中将T替换为Double后,与cast3相同,但cast2编译而cast3不相同。
因为Java泛型的工作方式不是用“ T
代替Double
”,而是使用擦除。泛型只是编译时的一件事。 cast2()
的实际实现是
return new ArrayList();
...完全没有<Anything>
。 cast2()
编译后,您可以使用任何名称调用它,而不必担心。