As advert suggests ClassCastException in Java comes when nosotros attempt to type shape an object in addition to object is non of the type nosotros are trying to shape into. In fact ClassCastException in Java is 1 of most mutual exception inward Java along alongside java.lang.OutOfMemoryError in addition to ClassNotFoundException inward Java earlier Generics was introduced inward Java v to avoid frequent instances of java.lang.classcastexception cannot hold upward shape to while working alongside Collection classes similar ArrayList in addition to HashMap, which were non type-safe earlier Java 5. Though nosotros tin minimize in addition to avoid java.lang.ClassCastException in Java past times using Generics in addition to writing type-safe parameterized classes in addition to method, its practiced to know existent movement of ClassCastException and How to solve it. In this Java tutorial nosotros volition run across Why java.lang.ClassCastException comes in addition to how to resolve ClassCastException in Java. We volition equally good run across how to minimize or avoid ClassCastException in Java past times using Generics, equally prevention is ever improve than cure.
Cause of java.lang.ClassCastException inward Java
In guild to sympathise movement of ClassCastException, y'all bespeak to hold upward familiar alongside concept of type casting inward Java. Since Java is an object oriented programming linguistic communication in addition to supports features similar Inheritance and Polymorphism, a reference variable of type rear degree tin correspond object of tyke class. This leads to ClassCastException if object is non of type on which y'all are casting it. It tin hold upward best explained alongside an example. Let's run across a sample code which volition throw ClassCastException in Java:
Object imObject = new String();
Integer i = (Integer) imObject;
Integer i = (Integer) imObject;
Above code volition throw
Exception inward thread "main" java.lang.ClassCastException: java.lang.String cannot hold upward shape to java.lang.Integer
at test.ClassCastExcetpionTest.main(ClassCastExcetpionTest.java:31)
If y'all run across closely nosotros were trying to shape an String object into an Integer object which is non right in addition to that’s why Java throws java.lang.classcastexception cannot hold upward shape to error. Problems tin instruct to a greater extent than hard if all degree are closely related. Since due to polymorphism inward Java an Object illustration tin agree whatever type of Object but y'all tin exclusively shape betwixt same type. what makes this work worse is that it exclusively comes during runtime, ClassCastException doesn't come upward at compile fourth dimension which makes it hard to uncovering peculiarly inward large firm Java application or high frequency electronic trading arrangement where input comes from upstream in addition to inward production diverse kinds of input are available. This was frequent work alongside Java Collection classes similar LinkedList in addition to HashSet inward Java which holds Object type but alongside introduction of Generics inward Java 5 solved this work past times checking type-safety during compile time. Which agency y'all tin non shop Integers on LinkedList of String, from Java v it volition effect inward compile fourth dimension error.
Common root of java.lang.ClassCastException
Following are simply about of the most mutual root of ClassCastExcepiton inward Java:
1. Java Collection classes similar HashMap, ArrayList, Vector or Hashtable which is non using Generics.
2. Methods which were written to stimulate got payoff of polymorphic behaviour in addition to coded on interfaces prior to Java v in addition to doesn’t used parameter to furnish type-safety. look for all places where y'all stimulate got used shape operator inward Java in addition to verify that whether that code is type-safe or not.
Here are simply about of the most oftentimes occurred ClassCastException inward Java:
java.lang.classcastexception java.lang.string cannot hold upward shape to java.lang.integer
This volition come upward when y'all attempt to shape String object to Integer i.e.
Integer lay out = (Integer) stringObject;
java.lang.classcastexception java.lang.string cannot hold upward shape to java.util.date :
This fault volition come upward when y'all shape String to Date inward Java, since both are non related to each other, it volition non possible to typecast them.
java.lang.classcastexception java.util.arraylist cannot hold upward shape to java.lang.string
I stimulate got seen this happening a lot inward beginners code based on Java Collection framework, Since ArrayList in addition to String are non related to each other, next casting volition throw this fault :
String str = (String) arrayListObject;
But if y'all definitely wants to convert ArrayList to String, than banking concern agree this post nearly converting collection to String inward Java.
Here are couplet of to a greater extent than examples, which is self explanatory.
java.lang.classcastexception java.util.arraylist cannot hold upward shape to java.util.map
java.lang.classcastexception ljava.lang.object cannot hold upward shape to ljava.lang.comparable
java.lang.classcastexception ljava.lang.object cannot hold upward shape to ljava.lang.integer
java.lang.classcastexception ljava.lang.object cannot hold upward shape to java.util.list
java.util.arraylist cannot hold upward shape to java.lang.comparable
How to prepare java.lang.ClassCastException inward Java
Solving ClassCastException can hold upward real slow 1 time y'all sympathise polymorphism inward Java in addition to difference betwixt compile fourth dimension in addition to runtime things. ClassCastException are elementary similar NullPointerException simply expect the stack-trace in addition to choke to the work number. Many of advanced Java IDE similar Eclipse in addition to Netbeans volition laissez passer on y'all hyperlink to navigate till culprit work lay out inward Java file. Now y'all know where just ClassCastException is coming in addition to stack draw equally good told which object it was trying to cast, Now y'all stimulate got to find, how that type of object comes in addition to this could stimulate got simply about fourth dimension based upon complexity of your coffee application. You tin equally good forbid ClassCastException in Java past times using Generics. Generics are designed to write type-safe code in addition to provides compile fourth dimension checks which tends to violate type-safety. By using Generics inward Collection classes in addition to other places y'all tin safely minimize java.lang.ClassCastException in Java.
That’s all on What is ClassCastException inward Java in addition to how to solve Exception inward thread "main" java.lang.ClassCastException. I highly recommend to role Generics piece using whatever Collection classes or degree which acts equally container e.g. ThreadLocal inward Java. Also write your ain classes in addition to method to stimulate got payoff of Generics to furnish type-safety equally shown inward this illustration of How to write parameterized class. It’s equally good a practiced take in to refresh your noesis on type-casting inward Java.
Further Learning
Complete Java Masterclass
How to solve java.util.NoSuchElementException inward Java