2017-06-22 52 views
0

在groovy中,當我更改克隆列表中的值時,原始值會被覆蓋。有誰知道如果我做錯了,或者它是一箇舊的Groovy錯誤?列表的克隆仍然糾正原始列表

我做這樣的事情:

List<Foo> myFooList = fooList.newFoos.findAll { it.type == "Types} 
List<Foo> newFoo = fooList.oldFoos.findAll { it.type == "Types}.clone() 

newFoo.each { 
    it.value = "neeeew value" 
} 

Foo fooOne = newFoo.each { foooo -> 
    fooTwo = fooList.oldFoos.find { it.id == foooo.id} 
    if(fooTwo.value != foooo.value) { 
     //Here it should go... but it turns out that fooTwo.value == foooo.value 
    } 
} 
+0

這個克隆的名單,而不是' Foo'。你需要做一個'... collect {new Foo(it.properties)}'(或類似的東西)而不是'clone' – cfrick

+1

你需要迭代這些項目並逐個克隆它們。爲了達到這個目的,你必須讓你的Foo類實現Cloneable接口和clone()方法。 – Piyush

+0

@cfrick他正在比較foo對象的基本屬性;儘管對象引用不相等,但它們的基本屬性是相等的。 – dsharew

回答

0

我通過添加元素的副本,以及解決問題,任何方式,它成爲了很多牛仔修復:

List<Foo> myFooList = fooList.newFoos.findAll { it.type == "Types} 
List<Foo> newFoo = fooList.oldFoos.findAll { it.type == "Types}.collect {it.clone()} 

newFoo.each { 
    it.value = "neeeew value" 
} 

Foo fooOne = newFoo.each { foooo -> 
    fooTwo = fooList.oldFoos.find { it.id == foooo.id} 
    if(fooTwo.value != foooo.value) { 
     //Here it should go... but it turns out that fooTwo.value == foooo.value 
    } 
} 
0

clone方法呼籲名單產生一個新的列表,但與它相同的對象。

你想用新的對象建立新的列表。這裏有一個例子:

@groovy.transform.ToString 
class Foo{ 
    String type 
    String value 
} 

def fooList = [ 
    new Foo(type:"Types", value:'old value1'), 
    new Foo(type:"Not", value:'old value2'), 
    new Foo(type:"Types", value:'old value3'), 
    new Foo(type:"Not", value:'old value4'), 
] 

def newFooList = fooList. 
    findAll{it.type=='Types'}. 
    collect{ new Foo(type:it.type, value:"new value") } //build new array with transformed elements 

//check the original list 
fooList.each{assert it.value!='new value'} 
//check new list 
newFooList.each{assert it.value=='new value'} 
assert newFooList.size()==2 

println fooList 
println newFooList 
+0

謝謝,但我問了克隆方法。任何方式你給我一個想法來解決它。收集{it.clone} – Dasma