What are the risks of explicitly casting from a list of type List<? extends MyObject> to a list of type List in Java?

后端 未结 5 1164
说谎
说谎 2021-01-12 16:26

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 o

5条回答
  •  逝去的感伤
    2021-01-12 16:34

    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 intList = new ArrayList();
        intList.add(2);
    
        List numList = intList;
        List strictNumList = (List) numList;
        strictNumList.add(3.5f);
    
        int num = intList.get(1); //java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
    

提交回复
热议问题