1

i heared that i should use compare() method for comparing two objects. instead of using - (substraction) directly. because -(substraction) can invoke overflow

public class Employee implements Comparable<Employee> {
... 
public int compareTo(Employee other) {
    return Double.compare(salary, other.salary);  // don't use (-)
}

}

and when i saw this implemented CompareTo() code(in Interger.class)

  public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

and i could see '>' but as i know it eventually would be using substraction like in c++... probably in interpreter.. if i'm right and use this result 0 ,1,-1 as = < >
what's different? why when i use compareTo() method i can avoid overflowing? please give me a detail reason.

hongse
  • 43
  • 3
  • *i know it eventually would be using substraction* What do you mean? Why do you think so? – shmosel Dec 10 '21 at 01:25
  • 1
    The thing you aren't supposed to do is `return salary - other.salary;` because that can overflow. Then you show an implementation that **doesn't** do that. So **what** are you asking? – Elliott Frisch Dec 10 '21 at 01:26
  • when i use '<' it would use substraction for compare two objects programmingly. doesn't it? – hongse Dec 10 '21 at 01:43
  • i want to know how compare two objects correctly when i use comparison operators (> < == ) – hongse Dec 10 '21 at 01:48
  • Computer-level subtraction will definitely consider overflow...```Integer.MIN_VALUE - 5``` is ```2147483643``` in Java, does the computer think that ```Integer.MIN_VALUE``` is greater than 5? – zysaaa Dec 10 '21 at 01:58

1 Answers1

0

As said in this post, the problem with using subtraction is the following.

This is due to integer overflow. When thisVal is very large and anotherVal is negative then subtracting the latter from the former yields a result that is bigger than thisVal which may overflow to the negative range.

https://stackoverflow.com/a/2728810/9520059

Indeed, the compiler will probably use a subtraction at very low level when evaluating the '<', however, it will check for overflows.

Leonard
  • 28
  • 5
  • 1
    "_Indeed, the compiler will probably use a subtraction at very low level when evaluating the '<', however, it will check for overflows._": comparing two integer values is such a basic concept that (most/all) modern CPUs have specific instructions for this (see https://stackoverflow.com/a/43844182 for information on the intel x64 architectur) – Thomas Kläger Dec 10 '21 at 08:09