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.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.