gpt4 book ai didi

groovy - 如何在 Groovy 中将元素添加到列表中?

转载 作者:行者123 更新时间:2023-12-03 07:56:51 26 4
gpt4 key购买 nike

假设我有一个 list ,就像这样......

def myList = ["first", 2, "third", 4.0];

如何将元素添加(推送)到它的末尾?我来自 PHP 背景,在那里我会做类似 $myList[] = "fifth"; 的事情。 . Groovy 中的等价物是什么?

最佳答案

documentation :

We can add to a list in many ways:


assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

你也可以这样做:
def myNewList = myList << "fifth"

关于groovy - 如何在 Groovy 中将元素添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com