简体   繁体   中英

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.

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

 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 ?

When i try catch the object direct with List reference variable, this work fine.

Arrays.asList returns a customly defined interpretation of List , it isn't java.util.ArrayList , but an AbstractList that is fixed-sized.

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> . 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).

static <T> Array.asList method returns a List<T> , not an 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.

The error indicates that the implementation returns an instance of an inner class defined in the Arrays class; the inner class is called ArrayList as well, but it has nothing to do with the ArrayList<T> defined in java.utils . 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.

You can initialize a new ArrayList with a List as parameter:

Integer[] ints = new Integer[]{2,4,3,9};
List<Integer> temp = Arrays.asList( ints );
ArrayList<Integer> testList = new ArrayList<Integer>(temp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM