我想执行一个副本并获得两个不同的对象,这样我就可以在不影响原件的情况下处理副本。
我有这个代码(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]]
这是怎么回事 ?