Category Archives: Convert

[Solved] ClassCastException :A cannot be cast to B : Example

java.lang.ClassCastException is RuntimeException and Unchecked Exception which throws when code has attempted to cast an object to a subclass or class of which it is not an instance.

How to Fix ClassCastException ?

  • Always careful when try to cast an object of a class into another class. Make sure that new  type class belongs to one of its parent classes.
  • Use Generics to prevent ClassCastException because Generics provide compile time checks to develop type-safe applications so that issue identified on compile time.

Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

Example :
Below are two example of ClassCastException where type casting an objet to different type which is not sub class of object class.

Example 1: Here first converting Integer Object to Object class which is parent class of all classes and then after type casting object of Object class to String Object. Which not compatible with Integer class and not sub class of Integer that’s why throwing ClassCastException.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ClassCastExceptionExample {

	public static void main(String[] args) {
		/**
		 * when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
	 */
		try
		{
		Object object= new Integer(10);
		System.out.println((String)object);
		}
		catch(ClassCastException ex)
		{
			ex.printStackTrace();
		}
	}

}

Example 2:
Here we  are trying to type cast an object of class A into an object of class B, and they aren’t compatible, we will get a class cast exception.

Let’s think of a collection of classes from below example

class A {}
class B extends A {…}
class C extends A {…}
We can cast any of these things to Object, because all Java classes inherit from Object.
We can cast either B or C to A, because they’re both “kinds of” A
We can cast a reference to an A object to B only if the real object is a B.
We can’t cast a B to a C even though they’re both A’s on that point will throw type cast exception.

public class A
{
}
public class B extends A
{
}
public class C extends A
{
}

package example;

public class ClassCastExceptionExample {

	public static void main(String[] args) {		

		try {
         A a=new A();
         A b=new B();
         A c=new C();

         B d=(B)b;
         B e=(B)c;// Exception on that point

		} catch (ClassCastException ex) {
			ex.printStackTrace();
		}
	}

}

Output:

java.lang.ClassCastException: example.C cannot be cast to example.B
	at example.ClassCastExceptionExample.main(ClassCastExceptionExample.java:27)
Advertisements

How to convert ArrayList to Array and Array to ArrayList?

Arrays class provide method Arrays.asList()  which convert array type elements to a unmodified fixed size ArrayList.

Same way List provide method as List.toArray(List) which convert ArrayList elements to Array.

Note : List returned from Arrays.AsList() is not like java.util.ArrayList. It
returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException

Example : 

In below example used method Arrays.asList()  to convert  String array to ArrayList of String elements. On other  side use List.toArray() method to convert ArrayList elements to Arrays of type String elements.

package exceptionhandeling;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayToArrayListConversion {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		System.out.println("*****Print ArrayList*****");
		printArrayList(empList);
		//Convert ArrayList to Array
		 empArr=(String[])empList.toArray();
		 System.out.println("*****Print Array*****");
		 printArray(empArr);
	}
	private static void printArrayList(List empList)
	{
		for(String emp:empList)
		{
			System.out.println(emp);
		}
	}
	private static void printArray(String[] empArr)
	{
		for(String emp:empArr)
		{
			System.out.println(emp);
		}
	}
}

Output:

*****Print ArrayList*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh
*****Print Array*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh