[Solved] java.lang.ClassCastException using Generics in Java

[Solved] java.lang.ClassCastException using Generics in Java

Generally when ever we write the Java Logic its better to know the issues during the compile time rather than at run time. If we do not use Generics we might face java.lang.ClassCastException when trying to add an Integer Object instead of String Object and try to retrieve the value and perform an operation on it will cause this exception. How do we overcome this using Generics we will learn from this tutorial.

Lets implement the Logic without using the Generics:

Executing this Program returns following output in the Console:

Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at org.h2k.javaprograms.ClassCastExceptionExample.main(ClassCastExceptionExample.java:15)

Lets implement the Logic using the Generics:
In the above program change the Line No:8 as follows:

List<String> strList = new ArrayList<String>();

Therefore implementing Generics avoids ClassCastException During run time. Any issues we can caught during Compile Time.

Leave a Reply

Your email address will not be published. Required fields are marked *