GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Update 1.5.md · ThreeParty/gradle-tutorial@2dd5f6d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Chapter 1 - Groovy 简介
    • 1.5.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Chapter 1 - Groovy 简介/1.5.md‎

Copy file name to clipboardExpand all lines: Chapter 1 - Groovy 简介/1.5.md
+62Lines changed: 62 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,67 @@ _Groovy的`List`使用非常方便,其实为了方便理解,完全可以把`
5959

6060
### 数组
6161

62+
在Groovy中,数组与`List`的格式是一样的,所以要使用数组形式,必须在定义时明确指类型或者强转(类似于使用非`ArrayList`的`List`类型):
63+
64+
```java
65+
String[] arr = ['AA', 'BB', 'CC']
66+
assert arr instanceof String[]
67+
68+
def num = [1, 2, 3] as int[]
69+
assert num instanceof int[]
70+
71+
//多维数组
72+
Integer[][] matrix = [[1,2], [3,4]]
73+
assert matrix instanceof Integer[][]
74+
```
75+
76+
数组的访问与`List`完全一致,这里就不赘述了
6277

6378
### `Map`
79+
80+
`Map`的语法类似于JSON数组,可使用两种形式访问/操作:
81+
82+
- `map['key']` 类似数组的访问形式
83+
- `map.key` 类似对象属性的访问形式
84+
85+
```java
86+
def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']
87+
assert colors['red'] == '#FF0000'
88+
assert colors.green = '#00FFFF'
89+
90+
colors['pink'] = 'FF00FF'
91+
colors.yellow = '#FFFF00'
92+
93+
//Groovy默认会使用`java.util.LinkedHashMap`来创建Map
94+
//要使用其他类型,请在声明时指定或使用强转
95+
assert colors instanceof java.util.LinkedHashMap
96+
```
97+
98+
如果访问一个不存在的key,则会返回null
99+
100+
`assert colors['white'] == null`
101+
102+
上述的`colors`在创建时,虽然key没有用引号,但是Groovy会使用String作为key,这样就会产生一个问题 - 如果key中包含变量怎么办,会不会重复或导致语义混淆(怎么知道red是一个字符串而不是先前定义过的变量)?
103+
104+
Groovy可以使用其他类型来作为key
105+
106+
```java
107+
def map = [1:'hello', 2:'world']
108+
assert map[1] == 'hello'
109+
```
110+
111+
因为数字不会导致语义混淆,因为他就是数字,不可能是变量,所以Groovy在创建上述Map时,就是用数字来作为key。
112+
113+
__除了数字之外,Groovy会将其他方式定义的key作为字符串存储,如果想要在key中使用变量,请使用小括号__
114+
115+
```java
116+
def key = 'name'
117+
118+
//此时map1中只有键名为'key'的映射,而不是'name'
119+
def map1 = [key: 'Mike']
120+
assert map1.contains('name')
121+
122+
//此时map2中只有键名为'name'的映射,而不是'key'
123+
def map2 = [(key): 'Mike']
124+
assert map1.contains('key')
125+
```

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.