【发布时间】:2021-12-10 01:22:48
【问题描述】:
我听说我应该使用 compare() 方法来比较两个对象。 而不是直接使用 - (减法)。因为 -(减法) 可以调用溢出
public class Employee implements Comparable<Employee> {
...
public int compareTo(Employee other) {
return Double.compare(salary, other.salary); // don't use (-)
}
}
当我看到这个实现的 CompareTo() 代码(在 Interger.class 中)
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
我可以看到'>'
但据我所知,它最终会像在 c++ 中一样使用减法......可能在解释器中......如果我是对的
并将结果 0 ,1,-1 用作 =
有什么不同?
为什么当我使用 compareTo() 方法时可以避免溢出?
请给我一个详细的理由。
【问题讨论】:
-
我知道它最终会使用减法你是什么意思?你为什么这么认为?
-
你不应该做的事情是
return salary - other.salary;,因为它可能会溢出。然后你展示一个不这样做的实现。那么你在问什么? -
当我使用 '
-
我想知道当我使用比较运算符时如何正确比较两个对象 (>
-
计算机级减法肯定会考虑溢出...
Integer.MIN_VALUE - 5在Java中是2147483643,计算机认为Integer.MIN_VALUE大于5吗?
标签: java