Java Sorting: sort an array of objects by property, object not allowed to use Comparable

samuraiseoul picture samuraiseoul · Sep 16, 2012 · Viewed 47.4k times · Source

I have a class, Library, that contains an array of Book objects, and I need to sort the array based off the properties of Book, either Title or PageNumber. The problem is im not allowed to use the Comparable class with Book. How would you recommend I sort the array of Books in library? Write my own sort? Or is there an easier way? If you need snippets of code, just ask!

Answer

Peter Lawrey picture Peter Lawrey · Sep 16, 2012

You can provide a Comparator for comparing any type you wish, Comparable or otherwise.

For Arrays and Collections you use

Arrays.sort(array, myComparator);
Collections.sort(list, myComparator);

Even sorted collections like TreeSet can take a custom Comparator

e.g.

Collections.sort(books, new Comparator<Book>() {
   public int compare(Book b1, Book b2) {
      return if b1 is greater return +1, if b2 is smaller return -1 otherwise 0
   }
});