Comparable vs. Comparator

Book.java
TestCollections.java

Classes should implement the Comparable interface to control their natural ordering.

Objects that implement Comparable can be sorted by Collections.sort() and Arrays.sort() and can be used as keys in a sorted map or elements in a sorted set without the need to specify a Comparator.

Interface
Comparable
+ compareTo(Object) : int
compareTo() compares this object with another object and returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the other object.

Use Comparator to sort objects in an order other than their natural ordering.

Interface
Comparator
+ compare(Object, Object) : int
+ equals(Object) : boolean
compare() compares its two arguments for order, and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
public class Book implements Comparable {
    String title;
    int    isbn;

    Book(String title, int isbn) {
        this.title = title;
        this.isbn  = isbn;
    }

    public int compareTo(Object object) {
        Book other = (Book) object;
        if (this.title.equals(other.title)) {
            return this.isbn - other.isbn;
        }
        return this.title.compareTo(other.title);
    }
}
import java.util.*;

public class TestCollections {
    public static void main(String[] args) {
        List list = new LinkedList();
        list.add(new Book("Patterns", 12345));
        list.add(new Book("Patterns", 34567));
        list.add(new Book("Examples", 23456));

        Collections.sort(list);

        Collections.sort(list, new Comparator() {
            public int compare(Object obj1, Object obj2) {
                Book book1 = (Book) obj1;
                Book book2 = (Book) obj2;
                return book1.isbn - book2.isbn;
            }
        });
    }
}