列表的克隆仍然更正原始列表

时间:2017-06-22 13:59:09

标签: groovy

在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
   }
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
   }
}