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

查看:293
本文介绍了添加元素的通配符类型的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.

这是给我这个错误

在1号线无法实例化ArrayList类型&LT ;?扩展问题&GT;

和上线#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...

添加东西通配符集合是危险的,因为你不知道什么样的问题的它实际上包含。它的可能的是 FreeResponseQuestion S,但它也不可能是,如果不是,那么你会得到 ClassCastException异常取值某处的道路。由于添加的东西通配符集合几乎总是失败,他们决定把运行时异常成编译时异常,并节省大家一些麻烦。

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&LT ;?扩展问题&GT; ?因为你不能由于上述原因添加任何东西给它这将是没用的。你几乎肯定要完全忽略通配符:

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天全站免登陆