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

Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

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

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;
}
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 this.id - emp.id;
}

 

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, this.id - emp.id 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 by Rishi Verma 1
...