【发布时间】:2015-05-21 21:48:22
【问题描述】:
我一直在反对这个问题一段时间,并认为也许一些新的眼睛会看到这个问题;感谢您的宝贵时间。
import java.util.*;
class Tbin<T> extends ArrayList<T> {}
class TbinList<T> extends ArrayList<Tbin<T>> {}
class Base {}
class Derived extends Base {}
public class Test {
public static void main(String[] args) {
ArrayList<Tbin<? extends Base>> test = new ArrayList<>();
test.add(new Tbin<Derived>());
TbinList<? extends Base> test2 = new TbinList<>();
test2.add(new Tbin<Derived>());
}
}
使用Java 8。在我看来,在test 中直接创建容器等同于test2 中的容器,但是编译器说:
Test.java:15: error: no suitable method found for add(Tbin<Derived>)
test2.add(new Tbin<Derived>());
^
如何写Tbin 和TbinList 以便最后一行可以接受?
请注意,我实际上将添加键入的 Tbins,这就是我在最后一行指定 Tbin<Derived> 的原因。
【问题讨论】:
-
在 Eclipse 中,错误消息是
The method add(Tbin<capture#1-of ? extends Base>) in the type ArrayList<Tbin<capture#1-of ? extends Base>> is not applicable for the arguments (Tbin<Derived>)。 -
试试这个
ArrayList<Tbin<? extends Base>> test3 = new TbinList<>();。确实很有趣。 -
@Radiodef Eclipse 显示错误消息“无法推断 TbinList 的类型参数”。
-
@TNT 是的。我很想说没有办法解决它。该错误证明无法将
TbinList转换为ArrayList<Tbin<? extends Base>>。 -
Related。虽然不确定这是一个确切的骗局。
标签: java generics bounded-wildcard