我只是好奇在将 raw 传递给 T 类型时生成的推断 T 类型是什么。它确实编译但有警告。
public class GenericMethodInference {
static <T> void test5(List<T t>){} // clause (5)
public static void main(String [] args) {
List e = new ArrayList<Integer>();
test5(e); // clause (6) // ok but with warning.
}
最佳答案
将原始类型分配给泛型类型将假定没有泛型约束(默认为 Object),但会删除可能存在的任何编译时类型安全保证。
But you cannot assign a raw to a
List <Object>
since it has been erased
听起来这里对类型删除存在根本性的误解。原始类型是泛型类型的最终结果。您指定了 List<Integer>
,编译器会根据该类型信息进行验证,然后删除 <Integer>
其中的一部分,从针对 List 的原始类型的操作中适本地插入对 Integer 的强制转换。
也就是说这两个检索操作是完全一样的。
List<Integer> integerList = new ArrayList<Integer>();
integerList.add(5);
Integer i = integerList.get(0);
Integer ii = (Integer)((List)integerList).get(0);
例如,以下是合法的。这只会给出警告(而不是导致编译器错误或运行时错误),因为我们正在对 Object 进行操作并且仍在所包含类型的适当范围内。
List<Object> objects = (List)integerList;
Object value = objects.get(0);
System.out.println(value);
它会打印出 5。如果你尝试做这样的事情,类型系统会提供帮助。
List<String> badStringList = integerList;
它会给你一个编译器错误,指出存在类型不匹配。但是,直接使用原始类型将抛弃所有类型安全性,并且完全依赖于您对应该使用的正确类型的判断。如果你弄错了,这会让你很容易搬起石头砸自己的脚。
List<String> badStringList = (List)integerList;
String badValue = badStringList.get(0); //ClassCastException is thrown at runtime
关于java - 如果我以原始类型作为参数调用泛型方法,将使用什么类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592260/