爲什麼java泛型如此棘手?我想我終於明白了,但是eclipse在下面的somOtherMethod中使用下面的getOuterList方法中的一行給出了一個錯誤。java中的簡單通用列表
protected List<?> getOuterList() {
// blah blah
}
protected List<? extends Object> getOuterList() {
// blah blah
}
protected void someOtherMethod() {
...
getOuterList().add((MyObject)myObject); //compile error
...
}
UPDATE:好 - 所以我現在明白了錯誤。這是我對List<?>
或List<? extends SomeObject>
確實意味着什麼缺乏瞭解。在前一種情況下,我認爲這意味着可以包含任何內容的列表。在後一種情況下,我認爲它是擴展SomeObject的一堆對象的列表。我的理解的正確表示將只是List<Object>
和List<SomeObject>
(不包括延伸)。我認爲延伸幫助我解決了一個他們不知道的問題。所以這裏是我真正的問題所在:
public interface DogKennel {
public List<Dog> getDogs();
}
public class GreyHoundKennel implements DogKennel {
protected List<GreyHound> greyHounds;
public List<GreyHound> getGreyHounds() {
return this.greyHounds;
}
public List<Dog> getDogs() {
// Is there no way to handle this with generics
// w/out creating a new List?
return getGreyHounds(); //compiler error
}
}
什麼是錯誤? – jjnguy 2009-07-15 18:16:23