将Arraylist <subclass>转换为ArrayList <parent> </parent> </subclass>

时间:2013-10-07 03:31:20

标签: java arraylist

我有两个包含ParentChild类的ArrayLists 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>

4 个答案:

答案 0 :(得分:6)

这是从父级转换为子级

的方法
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转换为父级的方式

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

答案 1 :(得分:3)

归功于Churro。

@SuppressWarnings("unchecked")
public Second(ArrayList<? extends Parent> child)
{
    super((ArrayList<Parent>) child);
}

答案 2 :(得分:0)

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

它不会投射,但它会创建一个新的Arraylist,内容为child

答案 3 :(得分:0)

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

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