compareTo()
中返回0
、返回1
和返回-1
有什么区别?在 Java 中?
最佳答案
官方定义
来自 Comparable.compareTo(T) 的引用文档:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
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."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
我的版本
简而言之:
this.compareTo(that)
返回
- 一个负整数如果这个<那个
- 0 如果这 == 那
- 一个正整数如果这个>那个
该方法的实现决定了<
的实际语义。 >
和 ==
(我的意思不是 java 的对象标识运算符意义上的 ==
)
示例
"abc".compareTo("def")
将产生小于 0 的值作为 abc
在 def
之前按字母顺序排列.
Integer.valueOf(2).compareTo(Integer.valueOf(1))
将产生大于 0 的值,因为 2 大于 1。
一些额外的点
注意:实现 Comparable 的类最好在 javadocs 中声明它的 compareTo() 方法的语义。
注意:您应至少阅读以下内容之一:
- Object Ordering部分 Sun Java 中的 Collection Trail 教程
- Effective Java经过 Joshua Bloch,尤其是第 12 项: 考虑实现 Comparable
- Java Generics and Collections经过 Maurice Naftalin,Philip Wadler,第 3.1 章:可比
警告:你不应该依赖 compareTo 的返回值是 -1
, 0
和 1
.您应该始终测试 x < 0
, x == 0
, x > 0
,分别。
关于java - Java 中 Comparable.compareTo 的返回值是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3767090/