410 APPENDIX B: Introduction to Groovy
Arrays
A Groovy array is a sequence of objects, just like a Java array (see Listing B-17).
Listing B-17. Creating and Using Arrays
- def stringArray = new String[3]
- stringArray[0] = "A"
- stringArray[1] = "B"
- stringArray[2] = "C"
- println stringArray
- println stringArray[0]
- stringArray.each { println it}
- println stringArray[-1..-3]
Line 1 creates a string array of size 3.
Lines 2 to 4 use an index to access the array.
Line 7 illustrates using the each() method to iterate through the array. The
each() method is used to iterate through and apply the closure on every
element.
Line 8 shows something interesting—it uses a range, which will be discussed
shortly, to access the array.
[A, B, C]
A
A
B
C
[C, B, A]
Lists
A Groovy list is an ordered collection of objects, just as in Java. It is an implementation of the
java.util.List interface. Listing B-18 illustrates how to create a list and common usages.
Listing B-18. Creating and Using Lists
- def emptyList = []
- def list = ["A"]
- list.add "B"
- list.add "C"
- list.each { println it }
- println list[0]
- list.set(0, "Vishal")
- println list.get(0)
- list.remove 2
- list.each { println it }