【发布时间】:2014-01-17 14:23:06
【问题描述】:
谁能解释一下在比较对象,更具体地说是它们的值时,下面的代码是否有任何区别。
代码 1
x.equals(y)
代码 2
x.compareTo(y) == 0
上面的代码可以互换吗?如果有,有什么区别?
【问题讨论】:
-
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." -
"当且仅当 e1.compareTo(e2) == 0 与 e1.equals(e2 ) 对于 C 类的每个 e1 和 e2。注意 null 不是任何类的实例,并且 e.compareTo(null) 应该抛出 NullPointerException 即使 e.equals(null) 返回 false。"
标签: java