You can read all about it in the
Comparable interface, and in the
Java™ Tutorials. Simply, if a class implements Comparable, you are saying it has a total ordering. That means for every pair of instances of that class, one of the following is always “true”:-
1: Instance 1 is “greater than” Instance 2.2: Instance 1 is “not different in rank from” Instance 2.3: Instance 1 is “less than” Instance 2.Obviously only one of those can be “true” at any one time. There is lots more in the Tutorials link I gave you.
Comparable is a parameterised interface, so you should always give a type, which actually makes writing the compareTo method easier.
I have just written “something” because I cannot predict the details of how to calculate the value for compareTo, but the links I gave should explain everything. In the second example, you don't have the cast, and there is no risk of passing the wrong type and suffering an Exception. You would have to consider what to do it
null is passed.
Go through the
List interface, the
Collections class and the
Java™ Tutorials to see what you can find out about sorting. You can also create a Stream from any List (Java8 only), and sort that Stream.