GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

What is the problem with following implementation of compareTo() method ?

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return -;
asked Oct 25, 2015 by Gaurav

2 Answers

Your code's   2nd line is wrong ,  you should typecast    o   not  the emp

corrected version will be - 

public int compareTo(Object o) {
	Employee emp = (Employee) o;
	return -;


answered Oct 26, 2015 by utkarsh111

I think the answer that we are looking here should be more inline with how minus operator works in compareTo.

Assuming id to be an Integer, - might give us erroneous results because of overflow, once integer crosses the max range in Java. Since, compareTo method only cares about the result being +ve or -ve, this might lead to absurd behaviour in the program.

One of the ways to achieve this neatly will be to use Integer.compareTo().



answered May 11, 2017 by Rishi Verma 1