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.OutOfMemoryErrorand 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 ArrayListand 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.
Read more »