gpt4 book ai didi

java - List 引用 List

转载 作者:搜寻专家 更新时间:2023-11-01 01:56:56 24 4
gpt4 key购买 nike

如果我有一个包含 A 类 child 列表的 A 类

public Class A
{
protected List<A> children = new ArrayList<A>();
...
}

那么在子类 B 中是否有可能拥有另一个类 C 的子类并创建对类 A 中子类列表的引用? A 类具有其他类想要使用的方法,例如送他们的 child 去。但是,A类是一般类,B类和C类比较具体。因此,为了使代码更容易阅读并避免大量类型转换,我希望父类(super class)的列表引用子类的列表。

所以当我更新otherChildren时,children列表也会更新。我想像下面的示例那样做一些事情,但是那行不通吗,它也不能转换为 (children = (List< A >) otherChildren)

但是有没有办法做到这一点呢?我真的很想避免所有类型转换,否则我会得到。

public Class B extends A
{
private List<C> otherChildren = new ArrayList<C>();

public B()
{
children = otherChildren;
...
// Modification of otherChildren will result in the same
// modification in children
}
}

public Class C extends A
{
...
}

最佳答案

你不能那样做,因为它们是不同的类型。您可以对 List<A> 的实例执行的操作之一是添加 A 的任意实例;你不能在 List<C> 上这样做因为它是一种更受限制的类型。

解决方法是使 A接受一个类型参数:

public class A <T extends A> {
protected List<T> children = new ArrayList<T>();
// ...
}

public class B extends A<C> {
private List<C> otherChildren = new ArrayList<C>();
public B() {
children = otherChildren;
}
// ...
}

public class C extends A<? extends A> {
// Or some such
}

当然,到时候你也可以说不需要otherChildren根本。可以直接在children上操作在子类中,它仍然可以在没有显式转换的情况下工作。

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