The important thing to ask when sorting objects is "does this class have a natural ordering". In other words, is there a sensible, default ordering that you'd want to use in the majority of case? If so, the best approach is to make the class implement
Comparable. In this case, presumably you want to sort alphabetically by title? Then you can do this:
If you've done that, the TreeSet will just work as you want it.
If the class doesn't have a natural ordering, or if you don't want to use the natural ordering in this particular case, then that's when you need a
Comparator. The code for creating the
TreeSet with a
Comparator is dead simple - there's a constructor that takes a
Comparator as an argument:
To create the comparator, just implement
Comparator<Book>. The
Java tutorials have a section giving more detail on all this at
http://download.oracle.com/javase/tutorial/collections/interfaces/order.html.