Adding an element inside a wildcard type ArrayList

纵然是瞬间 提交于 2019-11-28 02:18:32

Imagine the following scenario:

List<MultipleChoiceQuestion> questions = new ArrayList<MultipleChoiceQuestion>();
List<? extends Question> wildcard = questions;
wildcard.add(new FreeResponseQuestion()); // pretend this compiles

MultipleChoiceQuestion q = questions.get(0); // uh oh...

Adding something to a wildcard collection is dangerous because you don't know what kind of Question it actually contains. It could be FreeResponseQuestions, but it could also not be, and if it isn't then you're going to get ClassCastExceptions somewhere down the road. Since adding something to a wildcard collection will almost always fail, they decided to turn the runtime exception into a compile time exception and save everyone some trouble.

Why would you want to create an ArrayList<? extends Question>? It would be next to useless because you cannot add anything to it for the above reason. You almost certainly want to omit the wildcard entirely:

List<Question> id = new ArrayList<Question>();
id.add(new Identification(...));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!