casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Solution 1:
For me (using Java 1.6.0_26), the first snippet gives the same exception as the second one. The reason is that the Arrays.asList(..)
method does only return a List
, not necessarily an ArrayList
. Because you don't really know what kind (or implementation of) of List
that method returns, your cast to ArrayList<String>
is not safe. The result is that it may or may not work as expected. From a coding style perspective, a good fix for this would be to change your stuff
declaration to:
List<List<String>> stuff = new ArrayList<List<String>>();
which will allow to add whatever comes out of the Arrays.asList(..)
method.
Solution 2:
If you do this, you won't get any CCE:
ArrayList<ArrayList<String>> stuff = new ArrayList<ArrayList<String>>();
String[] titles = {"ticker", "grade", "score"};
stuff.add(new ArrayList<String>(Arrays.asList(titles)));
As the error clearly states, the class java.util.ArrayList
isn't the same as nested static class java.util.Arrays.ArrayList
. Hence the exception. We overcome this by wrapping the returned list using a java.util.ArrayList
.
Solution 3:
The problem is you specified your List to contain ArrayLists
- and by implication no other List implementations. Arrays.asList()
returns its own implementation of a List based on the implementation of the array parameter, which may not be an ArrayList. That's your problem.
More broadly, you have a classic code style problem: You should be referring to abstract interfaces (ie List
), not concrete implementations (ie ArrayList
). Here's how your code should look:
List<List<String>> stuff = new ArrayList<List<String>>();
String[] titles = { "ticker", "grade", "score" };
stuff.add((List<String>) Arrays.asList(titles));
I have tested this code, and it runs without error.