Java 强制转换到自定义阵列列表
我创建了一个自定义ArrayList对象,并在尝试强制转换到此对象时收到一个错误。我想我误解了一些事情,因为我认为这会起作用。如果我有一个只处理整数数组列表的自定义ArrayList对象:Java 强制转换到自定义阵列列表,java,arraylist,casting,Java,Arraylist,Casting,我创建了一个自定义ArrayList对象,并在尝试强制转换到此对象时收到一个错误。我想我误解了一些事情,因为我认为这会起作用。如果我有一个只处理整数数组列表的自定义ArrayList对象: public class CustomArrayList extends ArrayList<Integer>{ public void customMethod() { // do things with integer arraylist } } 公共类Cu
public class CustomArrayList extends ArrayList<Integer>{
public void customMethod() {
// do things with integer arraylist
}
}
公共类CustomArrayList扩展了ArrayList{
公共方法(){
//使用integer arraylist执行操作
}
}
我希望我可以像下面这样强制转换一个整数列表:
List<Integer> myList = new ArrayList<>();
((CustomArrayList) myList).customMethod();
List myList=new ArrayList();
((CustomArrayList)myList).customMethod();
但这会导致cast类异常。有人能解释一下我做错了什么,以及如何成功完成演员阵容吗?谢谢您的
CustomArrayList
是ArrayList
,但是ArrayList
不是CustomArrayList
如果要将任意ArrayList
转换为CustomArrayList
,可以编写:
List<Integer> myList = new ArrayList<>();
CustomArrayList customList = new CustomArrayList(myList);
customList.customMethod();
请注意,使用此构造函数创建的
CustomArrayList
实例是原始ArrayList
的副本,因此该实例中的更改不会反映在原始列表中,但是ArrayList
不是CustomArrayList
如果要将任意ArrayList
转换为CustomArrayList
,可以编写:
List<Integer> myList = new ArrayList<>();
CustomArrayList customList = new CustomArrayList(myList);
customList.customMethod();
请注意,使用此构造函数创建的CustomArrayList
实例是原始ArrayList
的副本,因此该实例中的更改不会反映在原始列表中将新建ArrayList()
更改为新建CustomArrayList()
更改新建ArrayList()
至新建CustomArrayList()
救生圈!这正是我想要的,并且帮助我理解为什么它不起作用。非常感谢!救生员!这正是我想要的,并且帮助我理解为什么它不起作用。非常感谢!