Java 强制转换到自定义阵列列表

Java 强制转换到自定义阵列列表,java,arraylist,casting,Java,Arraylist,Casting,我创建了一个自定义ArrayList对象,并在尝试强制转换到此对象时收到一个错误。我想我误解了一些事情,因为我认为这会起作用。如果我有一个只处理整数数组列表的自定义ArrayList对象: public class CustomArrayList extends ArrayList<Integer>{ public void customMethod() { // do things with integer arraylist } } 公共类Cu

我创建了一个自定义ArrayList对象,并在尝试强制转换到此对象时收到一个错误。我想我误解了一些事情,因为我认为这会起作用。如果我有一个只处理整数数组列表的自定义ArrayList对象:

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()
救生圈!这正是我想要的,并且帮助我理解为什么它不起作用。非常感谢!救生员!这正是我想要的,并且帮助我理解为什么它不起作用。非常感谢!