分类: Java
2009-06-05 15:05:12
8、循环
(1)while和do 循环
l Groovy支持Java相同的while和do 循环
x = 0
y = 5
while ( y-- > 0 ) {
x++
}
assert x == 5
x = 0
y = 5
do {
x++
}
while ( --y > 0 )
assert x == 5
(2)for循环
l Groovy的for循环更简单,而且能够和各种类型的数组、集合、Map等一起工作
// iterate over a range
x = 0
for ( i in 0..9 ) {
x += i
}
assert x == 45
// iterate over a list
x = 0
for ( i in [0, 1, 2, 3, 4] ) {
x += i
}
assert x == 10
// iterate over an array
array = (0..4).toArray()
x = 0
for ( i in array ) {
x += i
}
assert x == 10
// iterate over a map
map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
x += e.value
}
assert x == 6
// iterate over values in a map
x = 0
for ( v in map.values() ) {
x += v
}
assert x == 6
// iterate over the characters in a string
text = "abc"
list = []
for (c in text) {
list.add(c)
}
assert list == ["a", "b", "c"]
9、操作符重载
l Groovy支持操作符重载,使得数值、集合、Map和其它种类的数据结构更容易使用
l 在Groovy中的各种操作符被映射到对象中调用的正规方法
Operator |
Method |
a + b |
a.plus(b) |
a - b |
a.minus(b) |
a * b |
a.multiply(b) |
a / b |
a.divide(b) |
a++ or ++a |
a.next() |
a-- or --a |
a.previous() |
a[b] |
a.getAt(b) |
a[b] = c |
a.putAt(b, c) |
a << b |
a.leftShift(b) |
a == b |
a.equals(b) |
a != b |
! a.equals(b) |
a === b |
Java中的 a == b |
a <=> b |
a.compareTo(b) |
a > b |
a.compareTo(b) > 0 |
a >= b |
a.compareTo(b) >= 0 |
a < b |
a.compareTo(b) < 0 |
a <= b |
a.compareTo(b) <= 0 |
l 注意:所有比较操作符已经对null处理了,以避免抛出java.lang.NullPointerException
a = null
b = "foo"
assert a != b
assert b != a
assert a == null
l 在不同类型的数值比较之前,Groovy会自动将数值的类型转换为更大范围的数值类型,因此,下面的例子是有效的:
Byte a = 12
Double b = 10
assert a instanceof Byte
assert b instanceof Double
assert a > b
10、正则表达式
l Groovy支持使用~”...”本地表示的正则表达式,另外还支持“=~”操作符(创建Matcher)
import java.util.regex.Matcher
import java.util.regex.Pattern
// same as assert ("cheesecheese" =~ "cheese").find()
assert "cheesecheese" =~ "cheese"
// lets create a regex Pattern
pattern = ~"a*b"
assert pattern instanceof Pattern
assert pattern.matcher("aaaab").matches()
// lets create a Matcher
matcher = "cheesecheese" =~ "cheese"
assert matcher instanceof Matcher
answer = matcher.replaceAll("edam")
assert answer == "edamedam"
l Matcher缺省会调用find()方法返回boolean值,因此可以使用=~与Perl的=~操作符的简单使用保持一致
l 对于上面的模式匹配的例子主要是演示Pattern的用法,其实可以简化为
assert ("aaaab" =~ "a*b").matches()