2

我有两个 ArrayLists,其中包含扩展和Parent扩展的ChildChildParentSecondFirst

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>吗?

4

4 回答 4

8

这是从父母投射到孩子的方式

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);
}

这就是从孩子投射到父母的方式

//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);
}
于 2013-10-07T03:47:47.223 回答
4

Churro 的功劳。

@SuppressWarnings("unchecked")
public Second(ArrayList<? extends Parent> child)
{
    super((ArrayList<Parent>) child);
}
于 2013-10-07T03:44:21.980 回答
1

在 .addAll(child)的构造函数中使用this.addAll(childsecond )

它不是铸造,但它会创建一个新Arraylist的内容child

于 2013-10-07T03:40:36.247 回答
0

这种关系是洁净的唯一方式是,如果在 的构造函数中Parent,您没有以任何方式修改输入列表,除非可能是为了清除它或向它添加空值。在这种情况下,您不妨将构造函数的参数类型First设为 be ArrayList<? extends Parent>。这样就不需要复制数组或进行不安全的强制转换。

我应该补充一点,除非您依赖于ArrayList类的特定属性,否则List<? extends Parent>会更好。

于 2013-10-07T04:13:04.397 回答