Chapter 04 The collective Groovy datatypes
Groovy support collection types: ranges, lists and maps.
how and what
language expressiveness,
语言的表达能力
how much does the code say what, instead of how.
Range
1..10 from 1 to 10
1..<10 from 1 to 9
10..1 reverse range
the range elements must implement ++, -- and <=>.
for in range loop
index -1 means last element.
Groovy的Command还是要少用,加上括号吧
List
java.util.List
list = new LinkedList()
list[0] = 1
an array from Java to Groovy => converted to a list
toList() method, convert a collection to a list
The list’s getAt() and putAt() are overloaded with the parameters: integer, integers, range,
list[0..2] returns a sublist, not a new list, changing in the sublist, change the original list.
list.inject(initial) { accumulator, index -> f(accumulator, index) }
duck typing
as long as something walks like a duck and talks like a duck,
we happily treat it as a duck.
Map
java.util.Map
access map
1. subscript operator map[key], getAt()
2. dot operator .
3. method get(), default value
ConcurrentModificationException structurelly changing while iterating, such as list.each
Copy Semantics and
Modify Semantics works on a copy of the collection, collect, find, grep
works in place, e.g. add()