Java Reference
In-Depth Information
Listing 1.2. A Java class to sort strings
Here we see a consequence of the triumph of the nouns over the verbs. The Comparator
interface has a compare method, and all we want to do is to supply our own implement-
ation of that method to Collections.sort . We can't implement a method, however,
without including it in a class. In this case, we supply our own implementation (sort by
length in decreasing order) via the awkward Java construct known as an anonymous inner
class. To do so, we type the word new followed by the name of the interface we're im-
plementing (in this case, Comparator ), open a brace, and stuff in our implementation,
all as the second argument to the sort method. It's an ugly, awkward syntax, whose only
redeeming feature is that you do eventually get used to it.
Here's the Groovy equivalent in script form:
def strings = ['this','is','a','list','of','strings']
Collections.sort(strings, {s1,s2 -> s2.size() - s1.size()} as Comparator)
assert strings*.size() == [7, 4, 4, 2, 2, 1]
First of all, I'm taking advantage of Groovy's native support for collections by simply de-
fining and populating a list as though it's an array. The strings variable is in fact a ref-
erence to an instance of java.util.ArrayList .
Search WWH ::




Custom Search