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

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

    You are correct about retrieving objects from typedList, this should work.

    The problem is when you later add more objects to typedList. If, for instance, MyObject has two subclasses A and B, and wildcardList was of type A, then you can't add a B to it. But since typedList is of the parent type MyObject, this error will only be caught at runtime.

提交回复
热议问题