3、集合
Groovy支持集合、List、Map和数组
(1)Lists
l 下面是创建List的例子,[]表示空List表达式
list = [5, 6, 7, 8]
assert list.get(2) == 7
assert list instanceof java.util.List
emptyList = []
assert emptyList.size() == 0
emptyList.add(5)
assert emptyList.size() == 1
l 每个List表达式都是java.util.List的实现
(2)范围(Ranges)
l Range允许创建连续值的列表
l 由于Range扩展java.util.List,所以Range可以作为List使用
l 使用..的Range是包括两个边界,使用...的Range只包括开始边界,而不包括结束边界
// an inclusive range
range = 5..8
assert range.size() == 4
assert range.get(2) == 7
assert range instanceof java.util.List
assert range.contains(5)
assert range.contains(8)
// lets use an exclusive range
range = 5...8
assert range.size() == 3
assert range.get(2) == 7
assert range instanceof java.util.List
assert range.contains(5)
assert ! range.contains(8)
l Range可以用于实现java.lang.Comparable的Java对象
// an inclusive range
range = 'a'..'d'
assert range.size() == 4
assert range.get(2) == 'c'
assert range instanceof java.util.List
assert range.contains('a')
assert range.contains('d')
assert ! range.contains('e')
l Range可以用于循环遍历
for (i in 1..10) {
println "Hello ${i}"
}
(3)Maps
l 下面是创建Map的例子,[:]表示空Map表达式
map = ["name":"Gromit", "likes":"cheese", "id":1234]
assert map.get("name") == "Gromit"
assert map.get("id") == 1234
assert map instanceof java.util.Map
emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.put(5, "foo")
assert emptyMap.size() == 1
assert emptyMap.get(5) == "foo"
l Map可以象beans一样操作,但key值(类似属性名)必须为有效的String标识
map = ["name":"Gromit", "likes":"cheese", "id":1234]
assert map.name == "Gromit"
assert map.id == 1234
emptyMap = [:]
assert emptyMap.size() == 0
emptyMap.foo = 5
assert emptyMap.size() == 1
assert emptyMap.foo == 5
(4)使用下标操作符
l 可以在字符串、Lists、Maps...中使用下标进行索引
text = "nice cheese gromit!"
x = text[2]
assert x == "c"
assert x.class == String
sub = text[5..10]
assert sub == 'cheese'
map = ["name":"Gromit", "likes":"cheese", "id":1234]
assert map['name'] == "Gromit"
list = [10, 11, 12]
answer = list[2]
assert answer == 12
list = 100..200
sub = list[1, 3, 20..25, 33]
assert sub == [101, 103, 120, 121, 122, 123, 124, 125, 133]
l 可以使用下标操作符更新项目
list = ["a", "b", "c"]
list[2] = "d"
list[0] = list[1]
list[3] = 5
assert list == ["b", "b", "d", 5]
l 可以使用负索引从最后开始计数
text = "nice cheese gromit!"
x = text[-1]
assert x == "!"
name = text[-7..-2]
assert name == "gromit"
l 也可以使用向后范围(开始索引大于结束索引),返回的结果是反转的
text = "nice cheese gromit!"
name = text[3..1]
assert name == "eci"
本文地址:http://com.8s8s.com/it/it15327.htm