java - 使用相等和可比较接口(interface)的对象比较

标签 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/

相关文章:

java - 使用数组将数字相加并垂直打印总和

java - 我可以在具有多个实例的类上使用 Random 方法吗?

java - 对象数组[]

java - 当我尝试更改指定数组索引中的对象时,它会更改该对象的整个数组。有什么理由吗?

java - 如何解决变量在内部类中访问并且需要声明为final的问题

java - JCalendar 获取当前点击的日期

java - 如何拦截Spring MVC序列化响应?

java - java中如何从父类(super class)或后代类调用检查junit方法?

java swing图形颜色混合

java - 无法为 Java 进程设置 LD_LIBRARY_PATH