Java:将对象转换为通用类型 [英] Java: Casting Object to a generic type

查看:380
本文介绍了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泛型常见问题了解详情,特别是类型删除部分< a>。

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

这篇关于Java:将对象转换为通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆