Sunday, July 25, 2021

How to fix java.lang.classcastexception cannot be cast to in Java - cause and solution

As name suggests ClassCastException in Java comes when we try to type cast an object and object is not of the type we are trying to cast into. In fact ClassCastException in Java is one of most common exception in Java along with java.lang.OutOfMemoryError and ClassNotFoundException in Java before Generics was introduced in Java 5 to avoid frequent instances of java.lang.classcastexception cannot be cast to while working with Collection classes like ArrayList and HashMap, which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by using Generics and writing type-safe parameterized classes and method, its good to know real cause of ClassCastException and How to solve it.


In this Java tutorial we will see Why java.lang.ClassCastException comes and how to resolve ClassCastException in Java. We will also see how to minimize or avoid ClassCastException in Java by using Generics, as prevention is always better than cure.


Cause of java.lang.ClassCastException in Java

How to fix java.lang.ClassCastException in Java cause and solutionIn order to understand cause of ClassCastException, you need to be familiar with concept of type casting in Java. Since Java is an object oriented programming language and supports features like Inheritance and Polymorphism, a reference variable of type parent class can represent object of child class. This leads to ClassCastException if object is not of type on which you are casting it. It can be best explained with an example. Let's see a sample code which will throw ClassCastException in Java:

Object imObject = new String();
Integer i = (Integer) imObject;

Above code will throw
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at test.ClassCastExcetpionTest.main(ClassCastExcetpionTest.java:31)



If you see closely we were trying to cast an String object into an Integer object which is not correct and that’s why Java throws java.lang.classcastexception cannot be cast to error. Problems can become more difficult if all class are closely related. 

Since due to polymorphism in Java an Object instance can hold any type of Object but you can only cast between same type. what makes this problem worse is that it only comes during runtime, ClassCastException doesn't come at compile time which makes it hard to detect specially in large enterprise Java application or high frequency electronic trading system where input comes from upstream and in production various kinds of input are available. 

This was frequent problem with Java Collection classes like LinkedList and HashSet in Java which holds Object type but with introduction of Generics in Java 5 solved this problem by checking type-safety during compile time. Which means you can not store Integers on LinkedList of String, from Java 5 it will result in compile time error.



Common source of java.lang.ClassCastException

Following are some of the most common source of ClassCastExcepiton in Java:

1. Java Collection classes like HashMap, ArrayList, Vector or Hashtable which is not using Generics.
2. Methods which were written to take advantage of polymorphic behavior and coded on interfaces prior to Java 5 and doesn’t used parameter to provide type-safety.  look for all places where you have used cast operator in Java and verify that whether that code is type-safe or not.

Here are some of the most frequently occurred ClassCastException in Java:

java.lang.classcastexception java.lang.string cannot be cast to java.lang.integer

This will come when you try to cast String object to Integer i.e.
Integer number = (Integer) stringObject;

java.lang.classcastexception java.lang.string cannot be cast to java.util.date :
This error will come when you cast String to Date in Java, since both are not related to each other, it will not possible to typecast them.

java.lang.classcastexception java.util.arraylist cannot be cast to java.lang.string
I have seen this happening a lot in beginners code based on Java Collection framework, Since ArrayList and String are not related to each other, following casting will throw this error :

String str = (String) arrayListObject;

But if you definitely wants to convert ArrayList to String, than check this post about converting collection to String in Java

Here are couple of more examples, which is self explanatory.

java.lang.classcastexception java.util.arraylist cannot be cast to java.util.map
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.comparable
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.integer
java.lang.classcastexception ljava.lang.object cannot be cast to java.util.list
java.util.arraylist cannot be cast to java.lang.comparable
 

How to fix java.lang.ClassCastException in Java

Solving ClassCastException can be very easy once you understand polymorphism in Java and difference between compile time and runtime things. ClassCastException are simple like NullPointerException just look the stack-trace and go to the line number. Many of advanced Java IDE like Eclipse and Netbeans will give you hyperlink to navigate till culprit line number in Java file. 

Now you know where exactly ClassCastException is coming and stack trace also told which object it was trying to cast, Now you have to find, how that type of object comes and this could take some time based upon complexity of your java application. You can also prevent ClassCastException in Java by using Generics. 

Generics are designed to write type-safe code and provides compile-time checks which tends to violate type-safety. By using Generics in Collection classes and other places you can safely minimize java.lang.ClassCastException in Java.

That’s all on What is ClassCastException in Java and how to solve Exception in thread "main" java.lang.ClassCastException. I highly recommend to use Generics while using any Collection classes or class which acts as container e.g. ThreadLocal in Java. Also write your own classes and method to take advantage of Generics to provide type-safety as shown in this example of How to write parameterized class. It’s also a good idea to refresh your knowledge on type-casting in Java.


Other Java debugging and troubleshooting tutorials

10 comments :

Anonymous said...

Do you still see java.lang.ClassCastException in Generics world ? I thought this exception has been forgotten long back.

Anonymous said...

ClassCastException is result of bad design and bad coding. A carefully designed program will never see ClassCastException.

Farooq said...

Hi genius , how to resolve this ,

Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.Collection 

Anonymous said...

Hello folks, how do i find where to resolve the error in the code? here is the unexpected exception thrown ": java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double"

Manjula said...

[Ljava.lang.String; cannot be cast to java.util.Collection

Maxi said...

I have classCastException in CompateTo dunno why

Unknown said...

Exception in thread "main" java.lang.ClassCastException: java.io.FileInputStream cannot be cast to org.apache.pdfbox.io.RandomAccessRead

javin paul said...

Hello Unknown, this means RandomAccessRead doesn't implement FileInputStream, please check which super class it implements and use it accordingly

0793 said...

Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.heatcraft.model.PendingQuoteReportsModel


How to resolve error in this case ?

javin paul said...

what is PendingQuoteReportsModel, if its your class, make it to impelment List if you want to cast, otherwise just don't cast. If you provide more details on what you are doing, we may be able to help better.

Post a Comment