From Effective Java 2/e by Joshua Bloch
Comparable interface
public interface Comparable<T> { int compareTo(T t); }
By implementing Comparable, you allow your class to interoperate with all of the many generic algorithms and collection implementations that depend on this interface
public class WordList { public static void main(String[] args) { Set<String> s = new TreeSet<String>(); Collections.addAll(s, args); System.out.println(s); } }
General Contract
- Symmetric
sgn(x.compareTo(y)) == -sgn(y.compare- To(x))
- Transitive
(x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0
compareTo(y) == 0
implies thatsgn(x.compareTo(z)) == sgn(y.compareTo(z))
- It is strongly recommended, but not strictly required, that
(x.compareTo(y) == 0) == (x.equals(y))
compareTo method Example
public int compareTo(PhoneNumber pn) { // Compare area codes if (areaCode < pn.areaCode) return -1; if (areaCode > pn.areaCode) return 1; // Area codes are equal, compare prefixes if (prefix < pn.prefix) return -1; if (prefix > pn.prefix) return 1; // Area codes and prefixes are equal, compare line numbers if (lineNumber < pn.lineNumber) return -1; if (lineNumber > pn.lineNumber) return 1; return 0; // All fields are equal }