Tag Archives: ClassCastException

[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

Java : Comparable Vs Comparator


Comparable and Comparator both are interface used for compare and sorting collections of objects. Where  Comparable used for natural ordering of objects while Comparator used for sorting on user specific value on different type objects. In both the cases if objects are not equate or compatible will through ClassCastException.

In below links, I have explained about in depth detail about Comparable and Comparator implementation and cases where to use. Here mainly focus on some points for technical, implementation and functional points.

Comprable :Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

How to sort object by Comparator interface in ascending and descending order : JAVA

Difference between Comparable and Comparator

Comparable Comparator
Comparable is in java lang package as java.lang.Comparable. Comparator is in java util package as java.util.Comparator.
Method used int compareTo(Object t); Method used int compare(Object t1 , Object t2);

Comparable is used to compare itself by using with another object.

Here modify the class whose instance you want to sort. So that only one sort sequence can be created per class.

Comparator is used to compare two datatypes are objects.

Here build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class.

 A comparable used for default and natural ordering of objects.  A comparator represents the ordering itself for specific use.

Some java classes having build in Comparable interface like String, Date, Wrapper Classes etc.

Some classes actually provide Comparators for common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER.
 For sorting use methods like Collections.Sort(List) or Array.sort().  For Sorting use method Collections.sort(List, Comparator).

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

How to sort object by Comparator interface in ascending and descending order : JAVA


As in previous posts shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface and also sort user-defined classes by implements  Comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

Java : Comparable Vs Comparator

What is Comparator Interface?

java.util.Comparator  interface imposes user define sorting on different class fields  based on comparing values from different objects.  It provide compare() method which compares two objects  and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparator Interface?

Below is syntax of compare method:

public interface Comparator {
    public int compare(T o1, T o2);

}

compare() method compare two objects  fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparator interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparator  interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparable.

Note :  Below example is base on List of Employee objects it cannot be used to order a sorted collection, such as TreeSet because it generates an ordering that is not compatible with equals. It means that Comparator equates objects that the equals method does not.

In particular, any two employees who were joined on the same date will compare as equal. When you’re sorting a List this doesn’t matter; but when you’re using the Comparator to order a sorted collection, it’s fatal. If you use this Comparator to insert multiple employees joined on the same date into a TreeSet only the first one will be added to the set; the second will be seen as a duplicate element and will be ignored.

Example :

Below is simple Employee class which is having fields and getter/setter methods and also constructor to create object.

package sorting
public class Employee {
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{
}
//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}
}

Here we have created EmpComparator class and implements compare() method  of java.util.Comparator interface which will compare object fields values based on selected fields on time of sorting. ex: sortingField value.

For example : sortingField value as firstName then compare() method of  java.util.Comparator  interface will compare firstName value of passing two object on compare() method and return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;
import java.util.Comparator;

public class EmpComparator implements Comparator {
	public static final String ID = "id";
	public static final String FIRST_NAME = "firstName";
	public static final String LAST_NAME = "lastName";
	public static final String DESIGNATION = "designation";
	public static final String SALARY = "salary";
	public static final String AGE = "age";
	private String sortingField;

	@Override
	public int compare(Employee emp1, Employee emp2) {
		int diff = 0;
		switch (sortingField) {
		case ID:
			diff=emp1.getId()-emp2.getId();
			break;
		case FIRST_NAME:
			diff=emp1.getFirtsName().compareTo(emp2.getFirtsName());
			break;
		case LAST_NAME:
			diff=emp1.getLastName().compareTo(emp2.getLastName());
			break;
		case DESIGNATION:
			diff=emp1.getDesignation().compareTo(emp2.getDesignation());
			break;
		case SALARY:
			diff=(int)(emp1.getSalary()-emp2.getSalary());
			break;
		case AGE:
			diff=emp1.getAge()-emp2.getAge();
			break;

		}
		return diff;
	}

	public String getSortingField() {
		return sortingField;
	}

	public void setSortingField(String sortingField) {
		this.sortingField = sortingField;
	}
}

Here in below example creating List of Employee objects for sorting in ascending and descending order.

For sorting by firstName assigning value of sortingField as “firstName” in empComparator object. First we are using Collections.sort(List, Comparator) sorting method to sort list in ascending order by firstName because current value of sortingField is firstName. For descending order we will just reverse order of objects by Collections.resverse() method. Similarly using for lastName and also try with other fields of Employee class.

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

public class SortComparator {

	public static void main(String[] args) {
		Employee[] empArr = {
				new Employee(1, "Saurabh", "Gupta", "Sr Project Lead", 60000, 35),
				new Employee(2, "Gaurav", "Gupta", "Developer", 50000, 32),
				new Employee(3, "Shailesh", "Nagar", "Manager", 100000, 36),
				new Employee(4, "Ankur", "Mehrotra", "Lead", 55000, 30),
				new Employee(5, "Ranjith", "Ranjan", "Tester", 35000, 45),
				new Employee(6, "Ramesh", "Bhardwaj", "Support", 25000, 35)
				};
		// Convert Array to LIst
		List empList = Arrays.asList(empArr);
		// Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		// Sort List in Ascending order by first Name
		EmpComparator empComparator = new EmpComparator();
		empComparator.setSortingField("firstName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by FirtName
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

		// Sort List in Ascending order by lastName

		empComparator.setSortingField("lastName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by last Name
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList) {
		for (Employee emp : empList) {
			System.out.println(emp);<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
		}
	}
}

Output :

********Print Employee List Before Sort********
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]

********Print Employee List in Ascending Order********
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]

********Print Employee List in Descending Order********
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]

********Print Employee List in Ascending Order********
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]

********Print Employee List in Descending Order********
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

How to Sort By Comparable Interface in Ascending and Descending Order : Java


As in previous post shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to sort object by Comparator interface in ascending and descending order : JAVA

Java : Comparable Vs Comparator

What is Comparable Interface?

java.lang.Comparable  interface imposes a total natural ordering on the objects of each class that implements it.  it provide compareTo() method which compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparable Interface?

Below is syntax of compareTo method:

public interface Comparable {
    public int compareTo(T o);

}

compareTo() method compare current object (this)  fields values with passing object fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparable interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparable interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Example :

Below Employee class implements compareTo() method of  java.lang.Comparable  interface which is comparing firstName value with specified object firstName value. This  method return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;

public class Employee implements Comparable{
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{

}

//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

@Override
public int compareTo(Employee employee) {
	//sort by firstName
	return this.firtsName.compareTo(employee.firtsName);
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}

}

In below class sorting  Employee list objects by names in ascending order by Collections.sort(list). As shown above Employee Class implements  Comparable interface and it’s  compareTo() method  will sort elements in Ascending order by firstName on objects.

For Descending order used Collections.reverse(List) reverse method which will reverse list of sorted list.

 

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

public class SortComparable {

	public static void main(String[] args) {
		Employee [] empArr={
				new Employee(1,"Saurabh","Gupta","Sr Project Lead",60000,35),
				new Employee(2,"Gaurav","Gupta","Developer",50000,32),
				new Employee(3,"Shailesh","Nagar","Manager",100000,36),
				new Employee(4,"Ankur","Mehrotra","Lead",55000,30),
				new Employee(5,"Ranjith","Ranjan","Tester",35000,45),
				new Employee(6,"Ramesh","Bhardwaj","Support",25000,35)
				};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		//Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		//Sort List in Ascending order by collections api
		Collections.sort(empList);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		//Sort List in Descending order by collections api
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList)
	{
		for(Employee emp:empList)
		{
			System.out.println(emp);
		}
	}
}

 

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order


Collections framework provide Collections.sort(List) method which sort String elements in natural or chronological order or ascending order.

For descending order use Collections.reverse(List) method to reverse order of complete list elements.

Related Topics:

How to Sort By Comparable Interface in Ascending and Descending Order : Java

How to sort object by Comparator interface in ascending and descending order : JAVA

Java : Comparable Vs Comparator

Points to Remember:

  • Below are classes  implements  Comparable interface which provide a natural ordering for a class  sorted automatically.
  • If sorting a list of the elements which do not  implement Comparable , Collections.sort(list) method will throw ClassCastException. Similarly, Collections.sort(list, comparator ) will throw ClassCastException if you try to sort a list whose elements cannot be compared to another using Comparator.
                                 Classes Implementing Comparable
Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Example :
In below example sorting list of names in ascending order by Collections.sort(list). As shown above String Class by default having Comparable interface which will sort elements in Ascending or Chronological order.

For Descending order used Collections.reverse(List) reverse method which will reverse list of sorted list.

package sorting;

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

public class SortData {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		//Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		//Sort List in Ascending order by collections api
		Collections.sort(empList);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		//Sort List in Descending order by collections api
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList)
	{
		for(String emp:empList)
		{
			System.out.println(emp);
		}
	}

}

Output:

********Print Employee List Before Sort********
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh

********Print Employee List in Ascending Order********
Ankur
Gaurav
Ramesh
Ranjith
Saurabh
Shailesh

********Print Employee List in Descending Order********
Shailesh
Saurabh
Ranjith
Ramesh
Gaurav
Ankur

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html