Question
Why am I encountering a ClassCastException when casting Arrays.asList to ArrayList in Java?
List<String> list = Arrays.asList("One", "Two", "Three");
ArrayList<String> arrayList = (ArrayList<String>) list; // This line causes ClassCastException
Answer
The error occurs because the list returned by Arrays.asList() is an instance of a private static class that does not inherit from ArrayList. This results in a ClassCastException when casting to ArrayList directly.
List<String> originalList = Arrays.asList("Apple", "Banana", "Cherry");
ArrayList<String> arrayList = new ArrayList<>(originalList); // Correct way to create ArrayList from Arrays.asList()
Causes
- You are trying to cast the result of Arrays.asList() directly to ArrayList, which is incorrect because it's an instance of a different class (java.util.Arrays$ArrayList).
- Arrays.asList returns a fixed-size list backed by the specified array, not an ArrayList. Attempting to cast it will lead to ClassCastException.
Solutions
- To avoid this error, instead of casting, create a new ArrayList using the list returned from Arrays.asList(): List<String> list = Arrays.asList("One", "Two", "Three"); ArrayList<String> arrayList = new ArrayList<>(list);
- This way, you are creating a new ArrayList that contains the elements of the list.
Common Mistakes
Mistake: Directly casting the result of Arrays.asList to ArrayList.
Solution: Always use 'new ArrayList<>(list)' to create an ArrayList from the returned list.
Mistake: Assuming that the list returned by Arrays.asList is modifiable.
Solution: Understand that the list returned by Arrays.asList is fixed size and cannot be changed.
Helpers
- ClassCastException
- Arrays.asList
- ArrayList
- Java exception
- fixing ClassCastException
- Java casting error
- Java programming tips