2009-05-04 52 views
1

我想定义一个接口MyList,它是接口MyThing的列表。 MyList的部分语义是它的操作对没有实现MyThing接口的对象没有任何意义。通用接口:具体内容列表

这是正确的声明吗?

interface MyList<E extends MyThing> extends List<E> { ... } 

编辑:(部分2)现在我有一个返回MYLIST作为其方法之一,另一个接口。

// I'm defining this interface 
// it looks like it needs a wildcard or template parameter 
interface MyPlace { 
    MyList getThings(); 
} 

// A sample implementation of this interface 
class SpecificPlace<E extends MyThing> implements MyPlace { 
    MyList<E> getThings(); 
} 

// maybe someone else wants to do the following 
// it's a class that is specific to a MyNeatThing which is 
// a subclass of MyThing 
class SuperNeatoPlace<E extends MyNeatThing> implements MyPlace { 
    MyList<E> getThings(); 
    // problem? 
    // this E makes the getThings() signature different, doesn't it? 
} 

回答

2

是的,至少这是如何EnumSet这样做。

public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>


编辑在回答第2部分:

我不知道为什么getThings()在界面的返回类型不抱怨原始类型。我怀疑由于类型擦除,接口中的警告即使在那里也是无用的(如果将返回类型更改为List,则没有警告)。

对于第二个问题,由于MyNeatThing延伸MyThingE是其边界内。这就是在泛型参数中使用extends界限的点,不是吗?

+0

嘿等一下,刚刚发生的事情与名单是消费者,我们应该使用超级? – willcodejavaforfood 2009-05-04 17:05:16

+0

你不能在class类型参数声明中使用super,这使我无需找出答案。 ;) – 2009-05-04 17:07:53

1

对于第1部分来说,看起来是对的。

对于你的第2部分,我建议如下所示。该方法返回一个MyList的东西,你不知道它是什么(它显然是不同的),但你知道它是MyThing的子类型。

interface MyPlace { 
    MyList<? extends MyThing> getThings(); 
} 
0

请记住,像java.util.List的实现接口正确很难;所以问问自己所有的这些问题:

  • 我可以使用java.util.List的“原样”,不 我需要添加/删除功能?
  • 有没有更简单的我可以实现,就像Iterable <T>?
  • 我可以使用组合? (与继承)
  • 我可以在 现有库(如Google 集合)中找到 新想要的功能吗?
  • 如果我需要 添加/删除功能,是否值得 增加复杂性?

也就是说,你可能只是使用java.util。列表为你的例子:

interface MyPlace<T extends MyThing> { 
    List<T> getThings(); 
} 

class SpecificPlace implements MyPlace<MyThing> { 
    public List<MyThing> getThings() { return null; } 
} 

class SuperNeatoPlace implements MyPlace<MyNeatThing> { 
    public List<MyNeatThing> getThings() { return null; } 
}