我有两个包含Parent
和Child
类的ArrayLists Child
范围Parent
和Second
范围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>
?
答案 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>
会更好。