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

标签 java generics inheritance polymorphism java-8

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/

相关文章:

c# - 为什么在运行时出现通用约束冲突?

java - 如何使用泛型找到最大数量?

java - 在子类中调用父方法返回空值

java - 如何将数组的内容写入文本文件?

java - 在 OnGroupClickListener 中获取单击的组

java - 在 DispatcherServlet 中未找到名称为 'dispatcherServlet' 的 URI [/user] 的 HTTP 请求的映射

reactjs - React with Typescript——使用 React.forwardRef 时的泛型

java - 为什么大数组 java 很慢

java - 静态嵌套类可以通过非静态扩展

c# - 作为参数传递从 C# 中的类派生的对象