Java arrays cannot be changed in length, so you cannot add elements easily. One way is to convert the array to a java.util.List , add the element, and convert back. A second way is to construct a new array of size+1, copy the old values over, and set the new element to the last index position. Either takes some lines of code.
But Java arrays also have their benefits in terms of language support. They work with the subscript operator to easily retrieve elements of an array by index likemyarray[index] , or to store elements at an index position with myarray [index] = newElement .
We will demonstrate how Groovy lists give you the best of both approaches, extending the features for smart operator implementations, method overloading, and using lists as Booleans. With Groovy lists, you will also discover new ways of leveraging the power of the Java Collections API.
Listing 4.4 shows various ways of specifying lists. The primary way is with square brackets around a sequence of items, delimited with commas:
Lists can be created and initialized at the same time by calling toList on ranges.
- Listing 4.4 Specifying lists
Using list operators:
Lists implement some of the operators that you saw in section 3.3. Listing 4.4 contained two of them: the getAt and putAt methods to implement the subscript operator. But this was a simple use that works with a mere index argument. There’s much more to the list operators than that.
The subscript operator
The GDK overloads the getAt method with range and collection arguments to access a range or a collection of indexes. This is demonstrated in Listing 4.5.
- Listing 4.5 Accessing parts of a list with the overloaded subscript operator
Consequently, you get the last entry of a non-empty list with list[-1] and the next-to-last with list[-2]. Negative indexes can also be used in ranges, so list[-3..-1] gives you the last three entries. When using a reversed range, the resulting list is reversed as well, so list[4..0] is [4,3,2,1,0] . In this case, the result is a new list object rather than a sublist in the sense of the JDK. Even mixtures of positive and negative indexes are possible, such as list[1..-2] to cut away the first entry and the last entry.
Adding and removing items
Although the subscript operator can be used to change any individual element of a list, there are also operators available to change the contents of the list in a more drastic way. They are plus(Object) , plus(Collection) , leftShift(Object) , minus(Collection) , and multiply . Listing 4.6 shows them in action. The plus method is overloaded to distinguish between adding an element and adding all elements of a collection. The minus method only works with collection parameters.
- Listing 4.6 List operators involved in adding and removing items
Groovy lists are more than flexible storage places. They also play a major role in organizing the execution flow of Groovy programs. Listing 4.7 shows the use of lists in Groovy’s if , switch , and for control structures.
- Listing 4.7 Lists taking part in control structures
There are so many useful methods on the List type that we cannot provide an example for all of them in the language description. The large number of methods comes from the fact that the Java interface java.util.List is already fairly wide (25 methods in JDK 1.4).
Furthermore, the GDK adds methods to the List interface, to the Collection interface, and to Object . Therefore, many methods are available on the List type, including all methods of Collection and Object. While working with lists in Groovy, there is no need to be aware of whether a method stems from the JDK or the GDK, or whether it is defined in the List or Collection interface. However, for the purpose of describing the Groovy List datatype, we fully cover the GDK methods on lists and collections, but not all combinations from overloaded methods and not what is already covered in the previous examples. We provide only partial examples of the JDK methods that we consider important.
Manipulating list content
A first set of methods is presented in Listing 4.8. It deals with changing the content of the list by adding and removing elements; combining lists in various ways; sorting, reversing, and flattening nested lists; and creating new lists from existing ones.
- Listing 4.8 Methods to manipulate list content
Accessing list content
Lists have methods to query their elements for certain properties, iterate through them, and retrieve accumulated results. Query methods include a count of given elements in the list, min and max , a find method that finds the first element that satisfies a closure, and methods to determine whether any or every element in the list satisfies a closure. Iteration can be achieved as usual, forward with each or backward with eachReverse .
Cumulative methods come in simple and sophisticated versions. The join method is simple: It returns all elements as a string, concatenated with a given string. The injectmethod is inspired by Smalltalk. It uses a closure to inject new functionality. That functionality operates on an intermediary result and the current element of the iteration. The first parameter of the inject method is the initial value of the intermediary result. In listing 4.9, we use this method to sum up all elements and then use it a second time to multiply them.
- Listing 4.9 List query, iteration, and accumulation
The GDK introduces two more convenience methods for lists: asImmutable and asSynchronized . These methods use Collections.unmodifiableList andCollections.synchronizedList to protect the list from unintended content changes and concurrent access. See these methods’ Javadocs for more details on the topic.
Lists in action:
After all the artificial examples, you deserve to see a real one. Here it is: We will implement Tony Hoare’s Quicksort 1 algorithm in listing 4.10. To make things more interesting, we will do so in a generic way; we will not demand any particular datatype for sorting. We rely on duck typing—as long as something walks like a duck and talks like a duck, we happily treat it as a duck. For our use, this means that as long as we can use the < , = , and > operators with our list items, we treat them as if they were comparable.
The goal of Quicksort is to be sparse with comparisons. The strategy relies on finding a good pivot element in the list that serves to split the list into two sublists: one with all elements smaller than the pivot, the second with all elements bigger than the pivot. Quicksort is then called recursively on the sublists. The rationale behind this is that you never need to compare elements from one list with elements from the other list. If you always find the perfect pivot, which exactly splits your list in half, the algorithm runs with a complexity of n*log(n). In the worst case, you choose a border element every time, and you end up with a complexity of n^2 . In listing 4.10, we choose the middle element of the list, which is a good choice for the frequent case of preordered sublists.
- Listing 4.10 Quicksort with lists
If we had to explain the Quicksort algorithm without the help of Groovy, we would sketch it in pseudocode that looks exactly like listing 4.10. In other words, the Groovy code itself is the best description of what it does!
* Groovy > Document > Collections