Java Reference
In-Depth Information
Sets
A Groovy set is an unordered collection of objects, with no duplicates, just as in Java. It is an
implementation of java.util.Set . By default, unless you specify otherwise, a Groovy set is a
java.util.HashSet . If you need a set other than a HashSet , you can create any type of set by
instantiating it, as in def TreeSet = new TreeSet() . Listing B-22 illustrates how to create sets and
common usages.
Listing B-22. Creating and Using Sets
def set = ["A", "B" ] as Set
set.add "C"
println set
set.each { println it }
set.remove "B"
set.each { println it }
[A, B, C]
A
B
C
A
C
Creating an empty set is similar to creating an empty list. The difference is the addition of the Set
clause. One of the important differences between a list and a set is that a list provides indexed-
based access and a set doesn't.
Methods
Listing B-23 illustrates defining a method in Groovy the Java way, and Listing B-24 shows the same
thing but using the Groovy syntax instead.
Listing B-23. Defining a Method the Java Way
public String hello(String name) {
return "Hello, " + name;
}
Listing B-24. Defining a Method Using the Groovy Idiom
def hello(name) {
"Hello, ${name}"
}
 
Search WWH ::




Custom Search