java – 在通配符类型ArrayList中添加元素
作者:互联网
我试图在列表中添加一个元素,其中列表类型参数是扩展Question的通配符
ArrayList<? extends Question> id = new ArrayList<? extends Question>();
id.add(new Identification("What is my name?","some",Difficulty.EASY));
map.put("Personal", id);
识别是问题的子类. QUestion是一个抽象类.
它给了我这个错误
在线#1无法实例化类型ArrayList<?扩展问题>
在第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...
向通配符集合添加内容很危险,因为您不知道它实际包含哪种类型的问题.它可能是FreeResponseQuestions,但也可能不是,如果不是,那么你将在未来的某个地方获得ClassCastExceptions.由于向通配符集合中添加内容几乎总是会失败,因此他们决定将运行时异常转换为编译时异常并为每个人节省一些麻烦.
你为什么要创建一个ArrayList<?扩展问题>?它将是无用的,因为由于上述原因你无法添加任何东西.你几乎肯定想完全省略通配符:
List<Question> id = new ArrayList<Question>();
id.add(new Identification(...));
标签:bounded-wildcard,java,arraylist,generics,wildcard 来源: https://codeday.me/bug/20191002/1845551.html