Java Reference
In-Depth Information
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
1. def stringArray = new String[3]
2. stringArray[0] = "A"
3. stringArray[1] = "B"
4. stringArray[2] = "C"
5. println stringArray
6. println stringArray[0]
7. stringArray.each { println it}
8. println stringArray[-1..-3]
Line 1 creates a string array of size 3.
Lines 2 to 4 use an index to access the array.
each() method to iterate through the array. The
each() method is used to iterate through and apply the closure on every
element.
Line 7 illustrates using the
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
1. def emptyList = []
2. def list = ["A"]
3. list.add "B"
4. list.add "C"
5. list.each { println it }
6. println list[0]
7. list.set(0, "Vishal")
8. println list.get(0)
9. list.remove 2
10. list.each { println it }
 
Search WWH ::




Custom Search