Java:将对象转换为通用类型

Java:将对象转换为通用类型

问题描述:

在Java中,当从对象转换为其他类型时,为什么第二行产生与转换相关的警告,但第一行不会?

In Java when casting from an Object to other types, why does the second line produce a warning related to the cast, but the first one doesn't?

void a(Object o) {
  Integer i = (Integer) o;
  List<Integer> list = (List<Integer>) o;
}

/*Type safety: Unchecked cast from Object to List<Integer>*/


b

这是因为对象不会被检查为 List< Integer> code>在执行时由于类型擦除。它真的只是将它转换为列表。例如:

It's because the object won't really be checked for being a List<Integer> at execution time due to type erasure. It'll really just be casting it to List. For example:

List<String> strings = new ArrayList<String>();
strings.add("x");
Object o = strings;

// Warning, but will succeeed at execution time
List<Integer> integers = (List<Integer>) o;
Integer i = integers.get(0); // Bang!

请参阅 Angelika Langer的Java泛型常见问题了解详情,特别是类型删除部分。

See Angelika Langer's Java Generics FAQ for more info, particularly the type erasure section.