這聽起來有點微不足道,但我真的無法找到問題的癥結所在。是否可以超級演員名單?
List<Dog> dogs = getListOfDogs();
List<Cat> cats = getListOfCats();
feed(dogs);
feed(cats);
public void feed(List<Animal> animals) {
// feed the animal:
// depending on the type of animal, I might want to give it
// different kind of food.
}
class Dog implements Animal { /**/ }
class Cat implements Animal { /**/ }
interface Animal { /**/ }
我的環境非常類似於上面描述的環境。 我們還假設getListOfDogs
和getListOfCats
是固定的,並且沒有辦法在那邊採取行動。
當然,作爲擺在那的方式,這是一個非法代碼:feed
只接受List<Animal>
類型,而我只能List<Cat>
和List<Dog>
。
由於feed
是一種功能,幾乎相同的兩種動物,除了食物的種類(我可以通過instanceof
管理它),我想避免複製它,只是改變簽名。
有什麼方法可以超級投出兩個列表?像這樣的東西(這是顯然是不正確):feed((List<Animal>) getListOfDogs());
'feed'應該接受'List <?擴展動物>'。請參閱:https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html –
如果你還沒有看到它,那麼圍繞泛型和集合的討論很有用https://stackoverflow.com/questions/2723397/Java的泛型是什麼 - 是 - 佩奇 – beresfordt