Java Reference
In-Depth Information
B.4.2. Lists
Lists in Groovy are the same as lists in Java, except that the syntax is easier and there are
some additional methods available. Create a list in Groovy by including values between
square brackets:
def teams = ['Red Sox', 'Yankees']
assert teams.class == java.util.ArrayList
The default list is of type java.util.ArrayList . If you prefer to use a
LinkedList , instantiate it in the normal way.
Groovy has operator overloading. The Groovy JDK shows that the plus, minus, and left-
shift operators have been defined to work with lists:
teams << 'Orioles'
assert teams == ['Red Sox', 'Yankees', 'Orioles']
teams << ['Rays', 'Blue Jays']
assert teams ==
['Red Sox', 'Yankees', 'Orioles', ['Rays', 'Blue Jays']]
assert teams.flatten() ==
['Red Sox', 'Yankees', 'Orioles', 'Rays', 'Blue Jays']
assert teams + 'Angels' - 'Orioles' ==
['Red Sox', 'Yankees', ['Rays', 'Blue Jays'], 'Angels']
Accessingelementsofalistcanbedonewitharray-likesyntax.Again,thisisdonebyover-
riding a method—in this case, the getAt method:
assert teams[0] == 'Red Sox'
assert teams[1] == 'Yankees'
assert teams[-1] == ['Rays','Blue Jays']
As shown in figure B.1 , access to elements from the left end starts at index 0. Access from
the right end starts at index -1. You can use a range in the square brackets, too:
def cities = ['New York', 'Boston', 'Cleveland','Seattle']
assert ['Boston', 'Cleveland'] == cities[1..2]
Search WWH ::




Custom Search