java - Java 中 Comparable.compareTo 的返回值是什么意思?

标签 java comparable

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 的值作为 abcdef 之前按字母顺序排列.

Integer.valueOf(2).compareTo(Integer.valueOf(1))

将产生大于 0 的值,因为 2 大于 1。

一些额外的点

注意:实现 Comparable 的类最好在 javadocs 中声明它的 compareTo() 方法的语义。

注意:您应至少阅读以下内容之一:

警告:你不应该依赖 compareTo 的返回值是 -1 , 01 .您应该始终测试 x < 0 , x == 0 , x > 0 ,分别。

关于java - Java 中 Comparable.compareTo 的返回值是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3767090/

相关文章:

java - 利用继承和多态来绘制图像?

java - Java 1.8 版本的 Maven 安装问题

java - 从主要包含空值的 Comparables 列表中获取最小值和最大值的最佳方法是什么?

Java:使用 >、< 和 == 比较对象

java - Collections.sort() 不排序单个数字

java - 修改 DataSet 以接受 Comparable 对象

java - replaceAll 悬挂元字符

java - struts2中以.action后缀访问jsp路径

java - 视频中的 OpenCv 匹配模板 [Java]

java - Number 类 doubleValue 的异常