ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Comparable.compareTo的返回值在Java中意味着什么?

2019-09-30 01:04:05  阅读:237  来源: 互联网

标签:comparable java


Java中返回0,返回1和在compareTo()中返回-1之间有什么区别?

解决方法:

官方定义

来自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
>如果这是>则为正整数那

其中此方法的实现确定<的实际语义. &GT和==(我不是指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 by
约书亚布洛赫,特别是第12项:
考虑实施Comparable
> Java Generics and Collections by
Maurice Naftalin,Philip Wadler,第3.1章:可比较

警告:你永远不应该依赖compareTo为-1,0和1的返回值.你应该总是测试x< 0,x == 0,x> 0,分别.

标签:comparable,java
来源: https://codeday.me/bug/20190930/1834300.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有