开发者

java object hierarchy, and passing objects to functions

I have created a TreeMap like so:

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

I have created a constructor like so:

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

However, eclipse gives me a red squigly when I use the cons开发者_高级运维tructor, with my wrap variable as the single parameter:

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

An ArrayList is a type of Collection...yes? So why is this not working?


Generics don't work as you think they do in this case.

What you need is something similar to:

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

The ? is called a wild card. It will allow you to pass in a Collection, or anything that extends/implements Collection.

The line ? extends Collection<Spot> reads like:

Something that extends a Collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜