问题
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 FreeResponseQuestion
s, but it could also not be, and if it isn't then you're going to get ClassCastException
s 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