2012-11-09 40 views
5

我想執行復制並獲取兩個不同的對象,以便我可以在不影響原始文件的情況下處理副本。複製groovy中的列表清單

我有此代碼(常規2.0.5):

def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]] 
def b = a 
b.add([6,6,6,6,6,6]) 
println a 
println b 

產生:

[[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6, 6]] 
[[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6, 6]] 

好像b和a實際上是相同的對象

我可以修復它通過這種方式:

def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]] 
def b = [] 

a.each { 
    b.add(it) 
} 

b.add([6,6,6,6,6]) 
println a 
println b 

產生我想要的結果:

[[1, 5, 2, 1, 1], [one, five, two, one, one]] 
[[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6]] 

但是現在看看這個,在這裏我要原來的對象,並用獨特的副本,並進行排序元素:

def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]] 
def b = a 

b.each { 
    it.unique().sort() 
} 

println a 
println b 

產生:

[[1, 2, 5], [five, one, two]] 
[[1, 2, 5], [five, one, two]] 

如果我這次嘗試相同的修復程序,它不起作用:

def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]] 
def b = [] 

a.each { 
    b.add(it) 
} 

b.each { 
    it.unique().sort() 
} 

println a 
println b 

仍可產生:

[[1, 2, 5], [five, one, two]] 
[[1, 2, 5], [five, one, two]] 

這是怎麼回事?

+0

編輯標題,因爲這些列表,而不是陣列 –

回答

5

只需調用b = ab到被列表的相同實例(包含相同列表的實例)如a

調用帶a.each { b.add(it) }第二種方法裝置B點列表的不同實例,但內容的b是列表的相同情況,如a

你需要的是這樣的:

def b = a*.collect() 

b.each { 
    it.unique().sort() 
} 

所以a*.collect()使得每個列表列表中a

一個新的實例,您也可以做到這一點的一條線:

def b = a*.unique(false)*.sort(false) 

傳遞falseuniquesortstop those method changing the original lists,並強迫他們返回新列表實例。

(事實上,細心的當中,你會發現,sort不需要false傳遞給它,因爲我們已經有了一個新的實例感謝unique

+0

'.collectNested {}' –

2

Groovy中有Collection#collectNested,這是遞歸形式#collect。這將創建任意深度列表的副本。在版本1.8.1之前,它被稱爲#collectAll

final a = [ 
    'a', [ 'aa', 'ab', [ 'aba', 'abb', 'abc' ], 'ac', 'ad' ], 'b', 'c', 'd', 'e' 
] 

final b = a.collectNested { it } 
b[0] = 'B' 

final c = a.collectNested { it * 2 } 
c[0] = 'C' 

assert a as String == 
    '[a, [aa, ab, [aba, abb, abc], ac, ad], b, c, d, e]' 

assert b as String == 
    '[B, [aa, ab, [aba, abb, abc], ac, ad], b, c, d, e]' 

assert c as String == 
    '[C, [aaaa, abab, [abaaba, abbabb, abcabc], acac, adad], bb, cc, dd, ee]'