gpt4 book ai didi

java - 将 Arraylist<子类> 转换为 ArrayList<父类>

转载 作者:行者123 更新时间:2023-12-02 04:58:18 27 4
gpt4 key购买 nike

我有两个 ArrayList,其中包含 ParentChild哪个类Child范围ParentSecond延伸First

public First(ArrayList<Parent> parents)
{
// Parent Class's constructor
}

第二个类的构造函数

public Second(ArrayList<Child> child)
{
super(child);
// child class's constructor take ArrayList<Child>
}

是否可以施放ArrayList<Child>ArrayList<Parent>

最佳答案

这是从父级到子级的转换方式

public static void main(String[] args) {
ArrayList<Foo> parentArray = new ArrayList<Foo>();
parentArray.add(new Foo("tooLazy"));
parentArray.add(new Foo("tooAdd"));
parentArray.add(new Foo("tooMoreFields"));
ArrayList<Boo> childArray = (ArrayList<Boo>) ((ArrayList<?>) parentArray);
}

这就是从 Child 到 Parent 的转换方式

//Boo extends Foo BTW
public static void main(String[] args) {
ArrayList<Boo> parentArray = new ArrayList<Boo>();
parentArray.add(new Boo("tooLazy"));
parentArray.add(new Boo("tooAdd"));
parentArray.add(new Boo("tooMoreFields"));
ArrayList<Foo> childArray = (ArrayList<Foo>) ((ArrayList<?>) parentArray);
}

关于java - 将 Arraylist<子类> 转换为 ArrayList<父类>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216654/

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