[英]Java: Convert Arrays To List Exception
Arrays
class contain a function to convert arrays into list.When i convert the array of Integer
into ArrayList
it will throw an exception. Arrays
类包含一个将数组转换为list的函数。当我将Integer
数组转换为ArrayList
,它将引发异常。
Integer[] array = new Integer[]{2, 4, 3 , 9};
ArrayList<Integer> test = (ArrayList<Integer>) Arrays.asList(array);
The Arrays.asList(array)
return a List
of type Integer
, when i convert the list of Integer
to ArrayList
, it will throw an exception Arrays.asList(array)
返回一个Integer
类型的List
,当我将Integer
列表转换为ArrayList
,它会抛出一个异常
java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
ArrayList
implements the List
interface, so why this throw an exception ? ArrayList
实现了List
接口,为什么会抛出异常呢?
When i try catch the object direct with List
reference variable, this work fine. 当我尝试使用
List
引用变量直接捕获对象时,这工作正常。
Arrays.asList
returns a customly defined interpretation of List
, it isn't java.util.ArrayList
, but an AbstractList
that is fixed-sized. Arrays.asList
返回List
定义解释,它不是java.util.ArrayList
,而是一个固定大小的AbstractList
。
You will need to wrap all of the content in a new list: 您需要将所有内容包装在新列表中:
List<Integer> newList = new ArrayList<>(Arrays.asList(array));
Arrays#asList
doesn't return an ArrayList<T>
, it returns a List<T>
. Arrays#asList
不返回ArrayList<T>
,它返回List<T>
。 You don't know anything about the implementation of the List
, just that it adheres to the List
contract, with the documented limitations (the List
is fixed-size, so presumably doesn't implement the optional operations like List#add
that would change its size). 你对
List
的实现一无所知,只是因为它遵守了List
合同,并且有记录的限制( List
是固定大小的,因此可能没有实现像List#add
这样的可选操作会改变它的大小)。
static <T> Array.asList
method returns a List<T>
, not an ArrayList<T>
. static <T> Array.asList
方法返回List<T>
,而不是ArrayList<T>
。 You cannot assume that the implementation is going to return an ArrayList<T>
implementation of List<T>
- that's why you are getting an exception. 您不能假设实现将返回
List<T>
的ArrayList<T>
实现 - 这就是您获得异常的原因。
The error indicates that the implementation returns an instance of an inner class defined in the Arrays
class; 该错误表明该实现返回了
Arrays
类中定义的内部类的实例; the inner class is called ArrayList
as well, but it has nothing to do with the ArrayList<T>
defined in java.utils
. 内部类也称为
ArrayList
,但它与java.utils
定义的ArrayList<T>
无关。 A simple cast between the two will not work - if you must have a java.util.ArrayList<T>
, you need to create it yourself from the List<T>
returned by the asList
method. 两者之间的简单转换不起作用 - 如果必须有
java.util.ArrayList<T>
,则需要自己从asList
方法返回的List<T>
创建它。
You can initialize a new ArrayList
with a List
as parameter: 您可以使用
List
作为参数初始化新的ArrayList
:
Integer[] ints = new Integer[]{2,4,3,9};
List<Integer> temp = Arrays.asList( ints );
ArrayList<Integer> testList = new ArrayList<Integer>(temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.