Home  Collections intro  Lists  Maps  Sets  Which collection class?  Sorting  Hashing  Advanced
 Video lecture: hash tables  Bloom filters

Specifying how to sort data in Java: Comparators

So far, we've seen how to sort data that in Javaland is "naturally" sortable, i.e. implements the Comparable interface, or else make our own data implement Comparable so that it can be sorted. But of course this model has limitations:

  • if the class in question doesn't already implement Comparable– or doesn't implement it in the way you want– and you can't subclass it, then implementing Comparable isn't an option;
  • a single Comparable implementation is awkward if you want different sorting modes for the same class.

Java gets round these limitations with another interface, Comparator. A Comparator implementation provides a method specifying how any two objects of a given class are to be ordered. To specify how a collection of objects is to be sorted, Java then provides various places where we can "plug in" a Comparator of our choosing.

On the next page, we dive in and look at an example Comparator for sorting Strings by length.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved. If you have any feedback on the Java collections tutorials in this section or about the content of this site in general, please leave a message on the Javamex forum.