java对象层次结构,并将对象传递给函数

时间:2010-09-08 18:59:23

标签: java generics object

我创建了一个像这样的TreeMap:

TreeMap<Integer, ArrayList<MyClass>> wrap = new TreeMap<Integer, ArrayList<MyClass>>();

我创建了一个像这样的构造函数:

public foo (TreeMap<Integer, Collection<Spot> > objects) {
     this.field = objects;
}

但是,当我使用构造函数时,eclipse会给我一个红色的边框,我的wrap变量作为单个参数:

The constructor foo(TreeMap<Integer,ArrayList<Spot>>) is undefined

ArrayList是一种Collection ...是吗?那为什么这不起作用?

1 个答案:

答案 0 :(得分:2)

在这种情况下,泛型不像你认为的那样工作。

您需要的是类似于:

public foo (TreeMap<Integer, ? extends Collection<Spot> > objects) {
     this.field = objects;
}

?被称为外卡。它允许您传入Collection或任何扩展/实现Collection的内容。

? extends Collection<Spot>行的内容如下:

  

扩展集合的东西。

相关问题