1. Introduction

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

For a more in-depth introduction to exceptions in Java, take a look here.

2. ClassCastException Details

First, let's take a look at a simple example. Consider the following code snippet:

String[] strArray = new String[] { "John", "Snow" };
ArrayList<String> strList = (ArrayList<String>) Arrays.asList(strArray);
System.out.println("String list: " + strList);

The above code causes ClassCastException where we cast the return value of Arrays.asList(strArray) to an ArrayList.

The reason is that although the static method Arrays.asList() returns a List, we don't know until runtime exactly what implementation is returned. So at compile time the compiler can't know either and allows the cast.

When the code runs, the actual implementation is checked which finds that Arrays.asList() returns an Arrays$List thus causing a ClassCastException.

3. Resolution

We can simply declare our ArrayList as a List to avoid this exception:

List<String> strList = Arrays.asList(strArray);
System.out.println("String list: " + strList);

However, by declaring our reference as a List we can assign any class that implements the List interface, including the Arrays$ArrayList returned by the method call.

4. Summary

In this article, we've seen the explanation of what exactly is a ClassCastException and what measures we have to take this fix this issue.

The full code can be found over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!