ClassCastException at runtime test

Let us see the ClassCastException at runtime test in generics with the below example.

ClassCastException at run time test example:

GenericsTest.java

import java.util.ArrayList;
import java.util.List;
 
/**
 * This class is used to show the 
 * ClassCastException at runtime test.
 * @author javawithease
 */
public class GenericsTest {
	public static void main(String args[]){
		//Arraylist without generics.
		List list1 = new ArrayList();
		list1.add("Roxy");
		list1.add("Sandy");
		list1.add(new Integer(6));
		try{
			//Retrieve and print list elements.
			for(Object obj : list1){
				//ClassCastException at runtime when 
				//try to cast an integer to string.
		                String str=(String) obj;
		                System.out.println(str);
			}
		}catch(ClassCastException e){
			System.out.println();
			System.out.println();
			e.printStackTrace();
		}
 
 
		//Arraylist with generics.	
		List list2 = new ArrayList();
		list2.add("Roxy");
		list2.add("Sandy");
		list2.add("Sunil");
 
		//Retrieve and print list elements.
		for(String str : list2){
			//No ClassCastException at runtime 
			//because casting is not required.
	                System.out.println(str);
		}
 
	}
}

Output:

Roxy
Sandy
java.lang.ClassCastException: 
java.lang.Integer cannot be cast to java.lang.String
Roxy
Sandy
Sunil
at com.javawithease.business.GenericsTest.main
(GenericsTest.java:23)

Download this example.
 
Next Topic: Wildcard in generics.
Previous Topic: Compile time checking test.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.