Groovy天哪:从列表中删除最后一个项目[摘要]

Groovy Goodness: Removing the Last Item From Lists [Snippet]

2.5.0之前的Groovy版本对List对象末尾的项目的List类实现了不同的方法。 pop方法删除了List的最后一项,而push方法将一项添加到了List。 Groovy 2.5.0重新实现了这些方法,以便它们现在可以在List实例的第一项上使用。 要从List的末尾删除项目,我们可以使用新添加的方法removeLast

在下面的sampleGroovy代码中,我们使用removeLastadd方法删除项目并将其添加到列表的末尾。 使用poppush方法,我们可以删除项目并将其添加到List的开头:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def List = ['Groovy', 'is', 'great!']

// Remove last item from List
// with removeLast().
assert List.removeLast() == 'great!'
assert List == ['Groovy', 'is']

// Remove last item which is now 'is'.
List.removeLast()

// add new item to end of the List.
List.add 'rocks!'

assert List.join(' ') == 'Groovy rocks!'


/* IMPORTANT */
/* pop() and push() implementations has changed */
/* in Groovy 2.5.0. They now work on the first */
/* item in a List instead of the last. */

// Using pop() we remove the first item
// of a List.
assert List.pop() == 'Groovy'

// And with push we add item to
// beginning of a List.
List.push 'Spock'

assert List.join(' ') == 'Spock rocks!'

用Groovy 2.5.0编写。