2009-05-04 57 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; } 
}