在通配符类型 ArrayList 中添加元素 [英] Adding an element inside a wildcard type ArrayList

查看:36
本文介绍了在通配符类型 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);

其中识别是问题的子类.QUEstion 是一个抽象类.

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

它给了我这个错误

在第 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)

为什么会显示这样的错误?是什么原因造成的?我该如何解决?

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

推荐答案

想象以下场景:

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.它可能FreeResponseQuestions,但也可能不是,如果不是,那么你将在某处得到ClassCastExceptions在路上.由于向通配符集合添加内容几乎总是会失败,因此他们决定将运行时异常转换为编译时异常,为大家省去一些麻烦.

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.

为什么要创建一个ArrayList?它几乎没用,因为由于上述原因你不能向它添加任何东西.您几乎肯定想完全省略通配符:

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

这篇关于在通配符类型 ArrayList 中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆