gpt4 book ai didi

java - 在一行中将 child 列表转换为 parent 列表

转载 作者:行者123 更新时间:2023-11-29 10:11:57 25 4
gpt4 key购买 nike

BananaList 转换为 FruitList ...

public class Fruit { }

public class Banana extends Fruit { }

public List<Banana> allBananas() {
return new ArrayList<>(Arrays.asList(new Banana(), new Banana()));
}

...在返回之前我必须执行以下两个步骤:

public List<Fruit> getFruits() {
List<? extends Fruit> fruits = (List<? extends Fruit>) allBananas();
return (List<Fruit>) fruits;
}

为了避免中间步骤,可以这样做:

public List<Fruit> getFruits() {
return allBananas().stream().collect(Collectors.toList());
}

但在这种情况下,我必须创建新的 List 对象,这在性能方面不是很好。

我想我不明白某些事情,也许做错了。我想知道我的代码是否完全正确和安全?如果是这样 - 有更好的转换方式吗?如果不是 - 哪里出了问题并且可以改进?

最佳答案

除了将方法签名更改为 List<? extends Fruit> , 你可以使用 Collections.unmodifiableList获得只读 List<Fruit> View List<Banana> :

public List<Fruit> getFruits() {
List<Banana> bananas = getBananas();
return Collections.unmodifiableList(bananas);
}

两者都是 unmodifiableList并将方法声明为 List<? extends Fruit>服务于相同的目标——防止此方法的客户端将橙子添加到香蕉列表中。

关于java - 在一行中将 child 列表转换为 parent 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410356/

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