A List l may be sorted as follows:
Collections.sort (l);
If the list is composed of String elements, it is sorted alphabetically by dictionary; If it is made up of Date elements, it will be sorted in chronological order. How does Java know how to do this? This must be a trick! Fact In fact, both String and Date implement the comparable interface. The comparable interface provides a natural sort (natural ordering) for a class that allows objects of that class to be sorted automatically. The following table lists the JDK classes that implement the comparable:
Class Natural Sort
Byte-Signed numeric sorting
Character Numeric sorting without symbols
A Long signed numeric order
integer-Signed numeric sorting
Short signed numeric sorting
Double-Signed numeric sorting
Float-Signed numeric sorting
BigInteger Numeric sorting with symbols
BigDecimal Numeric sorting with symbols
The File-dependent system is sorted by path name parent order
String Sorted Alphabetically
Date chronologically sorted
Collationkey specific character sets in alphabetical order
If you want to sort a list whose elements do not implement comparable, Collections.sort (list) throws out a classcastexception. Similarly, if you want to sort a list whose elements are not compared to each other, Collections.sort throws a classcastexception. Elements that can be compared to each other are called mutually comparable (which can be compared). Although different types of elements may be compared to each other, any of the JDK types listed above do not allow comparisons between classes (Inter-class comparison).
If you just want to sort the list of comparable elements, or create a sorted set of objects for them, that's all you really need to know about the comparable interface. If you want to implement your own comparable type, the next section will interest you.
Write your own type of comparable
The comparable interface is composed of a single method:
Public interface Comparable {
public int compareTo (Object o);
}