我正在尝试在列表中添加一个元素,其中列表类型参数是扩展问题的通配符
ArrayList<? extends Question> id = new ArrayList<? extends Question>();
id.add(new Identification("What is my name?","some",Difficulty.EASY));
map.put("Personal", id);
其中,identification 是 Question 的子类。 QUEstion 是一个抽象类。
它给了我这个错误
上线#1 Cannot instantiate the type ArrayList<? extends Question>
第 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)
为什么会出现这样的错误?是什么原因造成的?我该如何解决这个问题?
最佳答案
想象一下以下场景:
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...
向通配符集合中添加某些内容是危险的,因为您不知道 Question
是什么样的。它实际上包含。它可能是FreeResponseQuestion
s,但也可能不是,如果不是,那么您将得到 ClassCastException
就在路上的某个地方。由于向通配符集合添加某些内容几乎总是会失败,因此他们决定将运行时异常转变为编译时异常,从而为大家省去一些麻烦。
您为什么要创建 ArrayList<? extends Question>
?它几乎毫无用处,因为由于上述原因您无法向其中添加任何内容。您几乎肯定想完全省略通配符:
List<Question> id = new ArrayList<Question>();
id.add(new Identification(...));
关于java - 在通配符类型 ArrayList 中添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12082780/