Java – how does CompareTo work?
•
Java
I know CompareTo returns negative or positive results related to one string and another, but why:
public class Test { public static void main(String[] args) { String y = "ab2"; if(y.compareTo("ac3") == -1) { System.out.println("Test"); } } }
It's true
public class Test { public static void main(String[] args) { String y = "ab2"; if(y.compareTo("ab3") == -1) { System.out.println("Test"); } } }
So is it?
Solution
Comparable. The total contract of CompareTo (o) is returned
>Positive integer if greater than another object. > If it is lower than another object, it is a negative integer If this is equal to another object, > 0
In your example, "AB2" CompareTo ("AC3") = = - 1 and "AB2" CompareTo ("AB3") = = - 1 only means that "AB2" is lower than "AC3" and "AB3" Using these examples alone, you can't get anything about "AC3" and "AB3"
This result is expected because B precedes C in the alphabet (so "AB2" < "AC3") and 2 precedes 3 (so "AB2" < "AB3"): Java sorts the string lexicographically
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码