Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

java - Adding an element inside a wildcard type ArrayList

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...