Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compareTo() method returns classCastException

Tags:

java

compareto

Let's assume I have an Employee base class and Manager subclass which extends Employee.Now let's say I create an object x of type Employee and object y of type Manager and call x.compareTo(y) no exception is triggered and x and y is compared as Employees namely y is cast to an Employee but when I call y.compareTo(x) I get a classCastException.I need to know why this happens and how to prevent x.compareTo(y) to execute as x and y are from different classes.My idea is to use getclass() method in Reflection class like this:

if (getClass() != other.getClass()) 
throw new ClassCastException();

I also want to know is there any other way to implement this.

like image 617
user1613360 Avatar asked Jun 11 '26 01:06

user1613360


2 Answers

You should implement compareTo() in the class Employee and start it with:

Employee o = (Employee)other;

Then continue with comparing this to o - this will ensure you're comparing two Employees (which is the lowest common denominator).

like image 138
Nir Alfasi Avatar answered Jun 13 '26 02:06

Nir Alfasi


Because your Manager is an Employee but Employee is not a Manager See below

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

instance of can be usefull in such cases

like image 38
Deepak Avatar answered Jun 13 '26 00:06

Deepak