带有 ArrayList 的 Java 泛型 <?延伸A>添加元素 [英] Java Generic with ArrayList <? extends A> add element

查看:49
本文介绍了带有 ArrayList 的 Java 泛型 <?延伸A>添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ABCD 类,其中 B扩展 AC 扩展 AD 扩展 A.

I have classes A, B, C and D where B extends A, C extends A and D extends A.

我有以下 ArrayList ,每个都有一些元素:

I have the following ArrayLists each with a few elements in them:

ArrayList<B> b;
ArrayList<? extends A> mix = b;

我打算让变量 mix 包含 BCD 类型的元素.我尝试将 C 类型的元素添加到 mix 中,如下所示:

I intended for the variable mix to contain elements of type B, C or D. I tried to add an element of type C into mix like this:

mix.add(anElementOfTypeC);

但 IDE 不允许我这样做,它说:

But the IDE doesn't allow me to do so and it says:

anElementOfTypeC 无法通过调用方法转换为 CAP#1CAP#1 是新类型变量的转换:CAP#1 从捕获 ?扩展 A

anElementOfTypeC cannot be converted to CAP#1 by method of invocation conversion where CAP#1 is a fresh type-variable: CAP#1 extends A from capture of ? extends A

我是否使用了 <?正确扩展 A> 吗?我该如何解决?

Did I use the <? extends A> correctly? How can I resolve this?

推荐答案

ArrayList 表示扩展 A 的某种未知类型的 ArrayList.
该类型可能不是 C,因此您不能将 C 添加到 ArrayList.

ArrayList<? extends A> means an ArrayList of some unknown type that extends A.
That type might not be C, so you can't add a C to the ArrayList.

实际上,由于您不知道 ArrayList 应该包含什么内容,因此您无法向 ArrayList 添加任何内容.

In fact, since you don't know what the ArrayList is supposed to contain, you can't add anything to the ArrayList.

如果你想要一个可以保存任何继承 A 的类的 ArrayList,请使用 ArrayList.

If you want an ArrayList that can hold any class that inherits A, use a ArrayList<A>.

这篇关于带有 ArrayList 的 Java 泛型 &lt;?延伸A>添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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