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

后端 未结 5 1166
说谎
说谎 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:27

    Consider you do something like:

    List childClassList = new ArrayList();
    childClassList.add(childClassOneInstanceOne);
    childClassList.add(childClassOneInstanceTwo);
    
    List wildcardList = childClasslist; // works fine - imagine that you get this from a method that only returns List
    List typedList = (List) wildcardList; // warning
    
    typedList.add(childClassTwoInstanceOne); // oops my childClassList now contains a childClassTwo instance
    ChildClassOne a = childClassList.get(2); // ClassCastException - can't cast ChildClassTwo to ChildClassOne
    

    This is the only major problem. But if you only read from your list it should be ok.

提交回复
热议问题