从类型为List& lt;的列表中显式强制转换的风险是什么?扩展MyObject& gt;到类型为List& lt; MyObject& gt;的列表在Java中? [英] What are the risks of explicitly casting from a list of type List<? extends MyObject> to a list of type List<MyObject> in Java?

查看:52
本文介绍了从类型为List& lt;的列表中显式强制转换的风险是什么?扩展MyObject& gt;到类型为List& lt; MyObject& gt;的列表在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为标题应能说明所有内容,以防万一...

I think the title should explain it all but just in case...

我想知道以下Java代码片段会引起与转换相关的风险和潜在问题:

I want to know what risks and potential issues relating to casting can arise from the following snippet of Java code:

List<? extends MyObject> wildcardList = someAPI.getList();
List<MyObject> typedList = (List<MyObject>) wildcardList;

我的想法是,wildcardList中的所有对象都应该是MyObject的实例(确切类型或子类),因此,每当从typedList中检索对象时,都不应存在ClassCastException.这样对吗?如果是这样,为什么编译器会生成警告?

My thoughts are that all objects in the wildcardList should be an instance of MyObject (exact type or subclass) and so whenever objects are retrieved from typedList then there should never be a ClassCastException. Is this correct? If so why does the compiler generate a warning?

推荐答案

只要从列表中检索对象,应该没有问题.但是,如果您对它调用其他方法,则可能会导致运行时异常,如以下代码所示:

There should be no problem as long as just you retrieve objects from the list. But it could result in runtime exception if you invoke some other methods on it like the following code demonstrate:

    List<Integer> intList = new ArrayList<Integer>();
    intList.add(2);

    List<? extends Number> numList = intList;
    List<Number> strictNumList = (List<Number>) numList;
    strictNumList.add(3.5f);

    int num = intList.get(1); //java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer

这篇关于从类型为List&amp; lt;的列表中显式强制转换的风险是什么?扩展MyObject&amp; gt;到类型为List&amp; lt; MyObject&amp; gt;的列表在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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