(Item 11) Comparable
Why: by implementing comparable, your class can interoperate with many generic algorithms.
Contract: compare the object with another, return a negative integer, zero, or positive integer
Classes that depends on comparison
Sorted collection
TreeSet
TreeMap
Utility classes: Collections and Arrays
//Sample Code, for PhoneNumber class above
public int compareTo(Object o) {
PhoneNumber pn = (PhoneNumber)o;
// Compare area codes
if (areaCode < pn.areaCode)
return -1;
if (areaCode > pn.areaCode)
return 1;
// Area codes are equal, compare exchanges
if (exchange < pn.exchange)
return -1;
if (exchange > pn.exchange)
return 1;
// Area codes and exchanges are equal, compare extensions
if (extension < pn.extension)
return -1;
if (extension > pn.extension)
return 1;
return 0; // All fields are equal
}