Getting Groovy, Part II
Written By: James Williams
- 28 Jul 2006 -
Description: This tutorial introduces you to Groovy, a dynamically-typed scripting language for the Java Virtual Machine. Part II introduces for loops, switch-case, collections, and closures.
Collections
Groovy has built-in support for Java Collections. By default, they are all either ArrayLists or Maps unless specified.
ArrayLists
For Groovy collections, there is no new keyword or curly braces, just the elements of the array or hash separated by commas.
names = ["John", "Jake", "Kate" ] ages = [10, 12, 14]
To declare the arrays as non-dynamic, we can use the as keyword.
names2 = names as String[] ages2 = [11,13,15] as int[]
In the case of the ages and ages2 ArrayLists, the integers are promoted transparently to the Integer class. As in Java, primitives types can not be added to a dynamic array. Luckily, we don't have that problem.
Adding, Removing and Accessing Elements
In addition to the add and remove functions that are present in Java, Groovy ArrayLists add a couple shortcuts.
f = ['A', 'B', 'C'] f += ['D'] //is the same as f.add(new Character('D') f - = ['C']
An ArrayList can also be referenced like a plain array.
f[2] // returns the same value as f.get(2)
HashMaps
Returning to our previous example, we an declare a hashmap by listing the key, followed by a colon, then the value. In this case, our key is the name and the value is the age.
names_ages = ["John":10, "Jake":12, "Kate":14]
Groovy's hashmap unfortunately doesn't have any shortcuts for setting values so we have to use the put.
names_ages.put("Joe",15)
To retreive values, we can use the get function, or reference the key like a class variable.'); ?>
names_ages.Joe //is the same as names_ages.get("Joe")
If there is punctuation or anything that would cause Groovy to parse incorrectly, you must enclose it in quotes(single or double)
name_phone = ["Jean-Jacques":5551212, "Jean-Marie":5557687] name_phone.'Jean-Jacques'
Empty ArrayList and HashMaps are declared:
emptyArrayList = [] emptyHash = [:]