在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
>如果这是>则为正整数那
其中此方法的实现确定<的实际语义. >和==(我不是指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,分别.