这可能听起来有点微不足道,但我真的无法找到问题的症结所在.
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 { /**/ }
Run Code Online (Sandbox Code Playgroud)
我的上下文非常类似于上面描述的上下文.我们也假设getListOfDogs并且getListOfCats是固定的,并且没有办法在那一方采取行动.
当然,就像这样,这是一个非法的代码:feed只接受List<Animal>类型,而我只能List<Cat>和List<Dog>.
因为feed这两种动物几乎完全相同,除了食物的种类(我可以通过它来管理它instanceof),我想避免复制它,只是改变签名.
有没有办法超级投射两个名单?像这样的东西(这显然不正确):feed((List<Animal>) getListOfDogs());
你在寻找的是:
public void feed(List<? extends Animal> animals) {
Run Code Online (Sandbox Code Playgroud)
这将接受a List<Animal>,或List<Dog>a List<Cat>,或等等.您将无法添加任何内容animals,因为它可以是任何类型的列表.如果您访问某个项目,animals您将获得类型的引用Animal.
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |