A rudimentary little story about Java's compareTo.
I want people who say, "The result of compareTo is that you don't know which one is right away. "
compareTo always compares to 0The result of Comparable # compareTo should always be compared with 0.
You may see code comparing to -1 or 1, which is incorrect.
The following is quoted from JavaDoc of standard API (I emphasize it) did)
Return value: ** Negative integer ** if this object is less than the specified object, ** Zero ** if equal, ** Positive integer ** if greater
As mentioned above, there is no guarantee that fixed values such as -1 and 1 will be returned.
(Although it is often implemented to return -1 or 1)
You can read and write obediently by calling compareTo on the left side of the comparison operator [^ 1] and writing 0 on the right side.
compareTo
if (obj1.compareTo(obj2) == 0) {
System.out.println("obj1 = obj2");
}
if (obj1.compareTo(obj2) != 0) {
System.out.println("obj1 ≠ obj2");
}
if (obj1.compareTo(obj2) < 0) {
System.out.println("obj1 < obj2");
}
if (obj1.compareTo(obj2) <= 0) {
System.out.println("obj1 ≦ obj2");
}
if (obj1.compareTo(obj2) > 0) {
System.out.println("obj1 > obj2");
}
if (obj1.compareTo(obj2) >= 0) {
System.out.println("obj1 ≧ obj2");
}
If you make a thorough comparison with 0, you will not be confused by the result of compareTo.
[^ 1]: ==, <, etc.
Recommended Posts