`
Javabengou
  • 浏览: 170618 次
  • 性别: Icon_minigender_1
  • 来自: 郴州
社区版块
存档分类
最新评论

Java笨狗groovy学习笔记—Getting Started

阅读更多

(-)变量
你可以给变量赋值. 像下面:

x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x
x = false
println x
x = "Hi"
println x

 (二)Lists and Maps

Groovy已经内置支持两种重要的数据类型, lists 和maps((Lists就像java中的数组一样来操作))Lists用来存储有序集合数据,例如:

myList = [1776, -1, 33, 99, 0, 928734928763]

 你可以使用[]来存取给定的项(索引开始位置为0):

println myList[0]

 输出结果:

1776

你也可以使用size方法来等到 list 长度:

println myList.size()

  输出结果:

6

但是通常你并不需要List的长度,因为不像Java,循环遍历一个List中的所有元素的首选方法是each(),详细信息在本学习笔记的"Code as Data"章节。

另一个本地数据结构叫 map,map用来存储”关联数组“或”词典“,即无序非均匀的集合,命名数据。例如,我们存储名字的IQ分数:

scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ]

 注意,每个存储在map中的值都是不同的类型, Brett'是 integer,Pete是string, Andrew是floating 。

我们可以使用两种方法来访问map中的值:

println scores["Pete"]
println scores.Pete

 输出结果:

Did not finish
Did not finish

为map添加数据,语法与给list添加值类似,例如:

scores["Pete"] = 3

 随后取得其值:

println scores["Pete"]

 输出结果:

 3.

另外,你可以像下面这样创建空map和list:

emptyMap = [:](Map)
emptyList = [](List)
 

为了确定它们为空,可以像下列这样:

println emptyMap.size()
println emptyList.size()

 输出结果为0。

(三)Conditional Execution

任何一种语言的重要特性是在不同的条件下执行不懂的代码,简单的方法是使用"if":

amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)
{
println("Good morning")
} else {
println("Good evening")
}
 

上面的结果是:首先,他会判断()中表达式,随后依据结果是否为"true"或"false"来执行第一个或第2个代码块。注意"else"代码块不是必须的:

amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)
{
println("Have another cup of coffee.")
}
 

(四)Boolean Expressions

在很多编程语言中这个是很特别的数据类型,它用来表示真实值,”true“或"false".Boolean就像其他数据类型一样可以储存在一个变量中:

myBooleanVariable = true

 更多Boolean表达式操作符:

* ==
* !=
* >
* >=
* <
* <=

 他们相当直观:

titanicBoxOffice = 1234600000
titanicDirector = "James Cameron"
trueLiesBoxOffice = 219000000
trueLiesDirector = "James Cameron"
returnOfTheKingBoxOffice = 752200000
returnOfTheKingDirector = "Peter Jackson"
theTwoTowersBoxOffice = 581200000
theTwoTowersDirector = "PeterJackson"
titanicBoxOffice > returnOfTheKingBoxOffice  // evaluates to true
titanicBoxOffice >= returnOfTheKingBoxOffice // evaluates to true
titanicBoxOffice >= titanicBoxOffice         // evaulates to true
titanicBoxOffice > titanicBoxOffice          // evaulates to false
titanicBoxOffice + trueLiesBoxOffice < returnOfTheKingBoxOffice + theTwoTowersBoxOffice  //
evaluates to false
titanicDirector > returnOfTheKingDirector    // evaluates to false, because "J" is before "P"
titanicDirector < returnOfTheKingDirector    // evaluates to true
titanicDirector >= "James Cameron"           // evaluates to true
titanicDirector == "James Cameron"           // evaluates to true
 
4
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics