从类型List<列表中显式转换的风险是什么?扩展MyObject>到List< MyObject>类型的列表在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?

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

问题描述

我想标题应该解释一切,但以防万一...



我想知道下列情况会产生与铸造相关的风险和潜在问题Java代码片段:

 列表< ;?扩展MyObject> wildcardList = someAPI.getList(); 
列表< MyObject> typedList =(List< MyObject>)wildcardList;

我的想法是wildcardList中的所有对象都应该是MyObject的实例(确切类型或子类)所以无论何时从typedList中检索对象,都不应该存在ClassCastException。它是否正确?如果是这样,为什么编译器会产生一个警告?只要你从列表中检索对象,应该没有问题了。

。但是,如果您调用其他一些方法,它可能会导致运行时异常,如下面的代码所示:

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

列表< ;?扩展Number> numList = intList;
列表<号码> strictNumList =(List< Number>)numList;
strictNumList.add(3.5f);

int num = intList.get(1); //java.lang.ClassCastException:java.lang.Float不能转换为java.lang.Integer


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

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;

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&lt;列表中显式转换的风险是什么?扩展MyObject&gt;到List&lt; MyObject&gt;类型的列表在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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