Harmeet Singh Taara
Harmeet Singh Taara

Reputation: 6611

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.

Upvotes: 2

Views: 166

Answers (4)

Rogue
Rogue

Reputation: 11483

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

Upvotes: 4

Smokez
Smokez

Reputation: 382

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075615

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

Upvotes: 2

Related Questions