Adding an element inside a wildcard type ArrayList

江枫思渺然 提交于 2019-11-26 23:42:45

问题


I am trying to add an element in a list where the list type parameter is a wildcard that extends Question

    ArrayList<? extends Question> id  = new ArrayList<? extends Question>();
    id.add(new Identification("What is my name?","some",Difficulty.EASY));
    map.put("Personal", id);

Where identification is a subclass of Question. QUestion is an abstract class.

it is giving me this error

On Line #1 Cannot instantiate the type ArrayList<? extends Question>

And on Line #2

The method add(capture#2-of ? extends Question) in the type ArrayList<capture#2-of ? extends Question> is not applicable for the arguments (Identification)

Why is it showing an error like that? What is causing it? And how would I fix it?


回答1:


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(...));


来源:https://stackoverflow.com/questions/12082780/adding-an-element-inside-a-wildcard-type-arraylist

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