2014-09-21 104 views
14

比方說,我有一個列表,像這樣...如何將元素添加到Groovy中的列表中?

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

如何添加(推)的元素,它的結束?我來自PHP背景,在那裏我只會做一些像$myList[] = "fifth";。 Groovy中的相同之處是什麼?

回答

21

documentation

我們可以添加到列表中在許多方面:

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" 
相關問題