[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

[ad_1]

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList.

ClassCastException is runtime exception which indicate that code has tried to cast an object to a subclass which is not an instance.

Reason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Although static method Arrays.asList() returns List, it returns java.util.Arrays$ArrayList which is different from ArrayList, so when we try to cast Arrays.asList() to ArrayList, it throws exception.

Let’s understand with the help of example:

Output:

Here is source code of Arrays.asList() method.


As you can see that there is static inner class present in java.util.Arrays which is different from java.util.ArrayList.

Fixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Use ArrayList’s constructor

If you must have instance of java.util.ArrayList, then you can create ArrayList instance using ArrayList‘s constructor.

Here is complete program

Output:

[India, China, Bhutan]

Here is source code of ArrayList’s constructor

Assign Arrays.asList() to List reference rather than ArrayList

We can declare List rather than ArrayList to avoid the exception. Since java.util.Arrays$ArrayList implements List interface, we can assign it to List reference.

Here is complete program

Output:

[India, China, Bhutan]

That’s all about how to fix [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList.

[ad_2]

Leave a Comment