<分区>
任何人都可以向我解释一下,在比较对象(更具体地说是它们的值)时,下面的代码是否有任何差异。
代码 1
x.equals(y)
代码 2
x.compareTo(y) == 0
上面的代码可以互换吗?如果有的话有什么区别?
标签 java
<分区>
任何人都可以向我解释一下,在比较对象(更具体地说是它们的值)时,下面的代码是否有任何差异。
代码 1
x.equals(y)
代码 2
x.compareTo(y) == 0
上面的代码可以互换吗?如果有的话有什么区别?
最佳答案
来自 Comparable
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
正如@ZouZou 提到的
The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
这意味着它们不可互换。
在 java api 中发生这种情况的示例在 BigDecimal 中
import java.math.BigDecimal;
public class Test{
public static void main(String args[]) {
BigDecimal big = BigDecimal.ZERO;
BigDecimal zero = new BigDecimal("0.00");
System.out.println("Compare "+ (big.compareTo(zero) == 0) ); //prints true
System.out.println("Equals "+big.equals(zero)); // prints false
}
}
关于java - 使用相等和可比较接口(interface)的对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188109/