Java Reference
In-Depth Information
Listing 1.1. Sorting strings using the Collections.sort method
The collections framework supplies interfaces, like List , and implementation classes,
like ArrayList . The add method is used to populate the list. Then the java.util
.Collections utility class includes static methods for, among other things, sorting and
searching lists. Here I'm using the single-argument sort method, which sorts its argu-
ment according to its natural sort. The assumption is that the elements of the list are from
a class that implements the java.util.Comparable interface. That interface includes
the compareTo method, which returns a negative number if its argument is greater than
thecurrentobject,apositivenumberiftheargumentislessthanthecurrentobject,andzero
otherwise. The String class implements Comparable as a lexicographical sort, which
is alphabetical, but sorts capital letters ahead of lowercase letters.
We'll look at a Groovy equivalent to this in a moment, but let's consider another issue first.
What if you want to sort the strings by length rather than alphabetically? The String
class is a library class, so I can't edit it to change the implementation of the compareTo
method.It'salsomarkedfinal,soIcan'tjustextenditandoverridethe compareTo imple-
mentation. For cases like this, however, the Collections.sort method is overloaded
to take a second argument, of type java.util.Comparator .
The next listing shows a second sort of our list of strings, this time using the comparator,
implemented as an anonymous inner class. Instead of using a main method as in the previ-
ous example, here's a StringSorter class that sorts strings either using the default sort
or by length.
Search WWH ::




Custom Search