What is the difference between returning 0
, returning 1
and returning -1
in compareTo()
in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
take example if we want to compare "a" and "b", i.e ("a" == this)
The
compareTo()
method returns an int with the following characteristics:If thisObject < anotherObject
If thisObject == anotherObject
If thisObject > anotherObject
Official Definition
From the reference docs of Comparable.compareTo(T):
My Version
In short:
returns
where the implementation of this method determines the actual semantics of
<
>
and==
(I don't mean==
in the sense of java's object identity operator)Examples
will yield something smaller than 0 as
abc
is alphabetically beforedef
.will yield something larger than 0 because 2 is larger than 1.
Some additional points
Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.
Note: you should read at least one of the following:
Warning: you should never rely on the return values of compareTo being
-1
,0
and1
. You should always test forx < 0
,x == 0
,x > 0
, respectively.Answer in short: (search your situation)
It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".
Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.
I use this mnemonic :
You keep the signs and always compare the result of
compareTo()
to 0