|
|
Specifying how to sort data in Java: ComparatorsSo 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:
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.
Written by Neil Coffey. Copyright © Javamex UK 2010. 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. |