Note that String#compareTo 's lexicographic comparison will sort capital "Z" before lower-case "a." If you're alphabetizing mixed-case strings, you need locale-sensitive ordering. In case the link to localized ordering of strings goes dead, the thing to use is java.text.Collator.
the Object Ordering section of the Collection Trail in the Sun Java Tutorial Effective Java by Joshua Bloch, especially item 12: Consider implementing Comparable Java Generics and Collections by Maurice Naftalin, Philip Wadler, chapter 3.1: Comparable Warning: you should never rely on the return values of compareTo being -1, 0 and 1.
The compareTo method in your example specifies that when we compare two spaceships we are going to use the string value of their spaceshipClass. Furthermore, the compareTo method in your example uses the default implementation of comparing strings: This means that the strings are compared lexicographically (you can think of it as alphabetical).
Comparison using compareTo does not use correlation: correlation is a symmetric property, whereas compareTo is (or at least should be) anti-symmetric, at least in the sense that sign(a.compareTo(b)) = -sign(b.compareTo(a)).
How do I compare dates in between in Java? Example: date1 is 22-02-2010 date2 is 07-04-2010 today date3 is 25-12-2010 date3 is always greater than date1 and date2 is always today. How do I v...
compareTo(T object) comes from the java.lang.Comparable interface, implemented to compare this object with another to give a negative int value for this object being less than, 0 for equals, or positive value for greater than the other. This is the more convenient compare method, but must be implemented in every class you want to compare.
Option 3: Java String comparison with the compareTo method There is also a third, less common way to compare Java strings, and that's with the String class compareTo method.
The Java String class provides the .compareTo () method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana"). The return of this method is an int which can be interpreted as follows: returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
It's a good practice to implement compareTo method such that, when its return value is 0, it's like two objects are equals (e.g. firstK.compareTo(secondK) == firstK.equals(secondK)). You can also read Java documentation compareTo documentation.