Read Also: [Fixed] java.lang.IllegalMonitorStateException in Java with Examples
Let's dive deep into the topic:
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
As always, first, we will produce the java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList before moving on to the solution.1. Producing the exception
We can easily produce this exception by trying to cast Arrays.asList() to ArrayList as shown below in the example:
import java.util.ArrayList; import java.util.Arrays; public class ClassCastExceptionExample { public static void main(String args[]) { String[] games = {"Basketball", "Football", "Baseball"};ArrayList<String> listOfGames = (ArrayList) Arrays.asList(games);System.out.println(listOfGames); } }
Output:
Exception in thread "main" java.lang.ClassCastException: class java.util.Arrays$ArrayList cannot be cast to class java.util.ArrayList (java.util.Arrays$ArrayList and java.util.ArrayList are in module java.base of loader 'bootstrap')
at ClassCastException.main(ClassCastException.java:8)
Explanation:
Arrays.asList(games); this statement returns a List implementation (java.util.Arrays$ArrayList) that is not java.util.ArrayList. java.util.Arrays$ArrayList happens to have a class name of ArrayList but that's a nested class within Arrays. As a result, you can not cast it to java.util.ArrayList.
Solution1: Using ArrayList Constructor
We can easily fix the issue by using the ArrayList constructor as shown below in the example:
import java.util.ArrayList; import java.util.Arrays; public class ClassCastExceptionExample { public static void main(String args[]) { String[] games = {"Basketball", "Football", "Baseball"};ArrayList<String> listOfGames = new ArrayList(Arrays.asList(games));System.out.println(listOfGames); } }
Output:
[Basketball, Football, Baseball]
Solution 2: Assigning Arrays.asList() to List reference
Another way to fix the exception is by assigning the Arrays.asList() method to the List reference rather than ArrayList as shown below in the example:
import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class ClassCastExceptionExample { public static void main(String args[]) { String[] games = {"Basketball", "Football", "Baseball"};List<String> listOfGames = Arrays.asList(games);System.out.println(listOfGames); } }
Output:
[Basketball, Football, Baseball]
That's all for today. Please mention in the comments if you have any questions related to how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList.