gpt4 book ai didi

java - 是否可以对 List 进行超投?

转载 作者:行者123 更新时间:2023-12-03 19:05:05 25 4
gpt4 key购买 nike

这听起来可能有点微不足道,但我真的找不到问题的症结所在。

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 { /**/ }

我所处的环境与上述情况非常相似。我们还假设 getListOfDogsgetListOfCats是固定的,没有办法在那一边行动。

当然,按照这种方式,这是一个非法代码:feed只接受 List<Animal>类型,而我只能有 List<Cat>List<Dog> .

feed是两种动物几乎相同的功能,除了食物的种类(我可以通过 instanceof 管理它),我想避免复制它,只是更改签名。

有没有什么办法可以超投这两个榜单?像这样(这显然是不正确的):feed((List<Animal>) getListOfDogs());

最佳答案

你要找的是:

public void feed(List<? extends Animal> animals) {

这将接受 List<Animal> , 或 List<Dog> , 或 List<Cat> , 等等。您将无法向 animals 添加任何内容,因为它可以是任何类型的列表。如果您访问 animals 中的项目你会得到一个 Animal 类型的引用.

关于java - 是否可以对 List 进行超投?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com