26

如何在 Groovy 中深度复制地图地图?映射键是字符串或整数。这些值是字符串、原始对象或其他映射,以递归方式。

4

5 回答 5

32

一个简单的方法是这样的:

// standard deep copy implementation
def deepcopy(orig) {
     bos = new ByteArrayOutputStream()
     oos = new ObjectOutputStream(bos)
     oos.writeObject(orig); oos.flush()
     bin = new ByteArrayInputStream(bos.toByteArray())
     ois = new ObjectInputStream(bin)
     return ois.readObject()
}
于 2012-10-31T10:03:26.667 回答
10

为了对类中的每个成员进行深度复制,对于 Class 对象存在 newInstance()。例如,

foo = ["foo": 1, "bar": 2]
bar = foo.getClass().newInstance(foo)
foo["foo"] = 3
assert(bar["foo"] == 1)
assert(foo["foo"] == 3)

请参阅http://groovy-lang.org/gdk.html并导航到 java.lang、Class,最后是 newInstance 方法重载。

更新

我上面的例子最终是一个浅拷贝的例子,但我真正的意思是,一般来说,你几乎总是必须定义你自己可靠的深拷贝逻辑,也许使用 newInstance() 方法,如果 clone( ) 方法是不够的。这里有几种方法可以解决这个问题:

import groovy.transform.Canonical
import groovy.transform.AutoClone
import static groovy.transform.AutoCloneStyle.*

// in @AutoClone, generally the semantics are
//  1. clone() is called if property implements Cloneable else,
//  2. initialize property with assignment, IOW copy by reference
//
// @AutoClone default is to call super.clone() then clone() on each property.
//
// @AutoClone(style=COPY_CONSTRUCTOR) which will call the copy ctor in a 
//  clone() method. Use if you have final members.
//
// @AutoClone(style=SIMPLE) will call no arg ctor then set the properties
//
// @AutoClone(style=SERIALIZATION) class must implement Serializable or 
//  Externalizable. Fields cannot be final. Immutable classes are cloned.
//  Generally slower.
//
// if you need reliable deep copying, define your own clone() method

def assert_diffs(a, b) {
    assert a == b // equal objects
    assert ! a.is(b) // not the same reference/identity
    assert ! a.s.is(b.s) // String deep copy
    assert ! a.i.is(b.i) // Integer deep copy
    assert ! a.l.is(b.l) // non-identical list member
    assert ! a.l[0].is(b.l[0]) // list element deep copy
    assert ! a.m.is(b.m) // non-identical map member
    assert ! a.m['mu'].is(b.m['mu']) // map element deep copy
}

// deep copy using serialization with @AutoClone 
@Canonical
@AutoClone(style=SERIALIZATION)
class Bar implements Serializable {
   String s
   Integer i
   def l = []
   def m = [:]

   // if you need special serialization/deserialization logic override
   // writeObject() and/or readObject() in class implementing Serializable:
   //
   // private void writeObject(ObjectOutputStream oos) throws IOException {
   //    oos.writeObject(s) 
   //    oos.writeObject(i) 
   //    oos.writeObject(l) 
   //    oos.writeObject(m) 
   // }
   //
   // private void readObject(ObjectInputStream ois) 
   //    throws IOException, ClassNotFoundException {
   //    s = ois.readObject()
   //    i = ois.readObject()
   //    l = ois.readObject()
   //    m = ois.readObject()
   // }
}

// deep copy by using default @AutoClone semantics and overriding 
// clone() method
@Canonical
@AutoClone
class Baz {
   String s
   Integer i
   def l = []
   def m = [:]

   def clone() {
      def cp = super.clone()
      cp.s = s.class.newInstance(s)
      cp.i = i.class.newInstance(i)
      cp.l = cp.l.collect { it.getClass().newInstance(it) }
      cp.m = cp.m.collectEntries { k, v -> 
         [k.getClass().newInstance(k), v.getClass().newInstance(v)] 
      }
      cp
   }
}

// assert differences
def a = new Bar("foo", 10, ['bar', 'baz'], [mu: 1, qux: 2])
def b = a.clone()
assert_diffs(a, b)

a = new Baz("foo", 10, ['bar', 'baz'], [mu: 1, qux: 2])
b = a.clone()
assert_diffs(a, b)

我用于@Canonicalequals() 方法和元组 ctor。请参阅groovy 文档第 3.4.2 章,代码生成转换

进行深度复制的另一种方法是使用 mixins。假设您希望现有类具有深拷贝功能:

class LinkedHashMapDeepCopy {
   def deep_copy() {
      collectEntries { k, v -> 
         [k.getClass().newInstance(k), v.getClass().newInstance(v)]
      }
   }
}

class ArrayListDeepCopy {
   def deep_copy() {
      collect { it.getClass().newInstance(it) }
   } 
}

LinkedHashMap.mixin(LinkedHashMapDeepCopy)
ArrayList.mixin(ArrayListDeepCopy)

def foo = [foo: 1, bar: 2]
def bar = foo.deep_copy()
assert foo == bar
assert ! foo.is(bar)
assert ! foo['foo'].is(bar['foo'])

foo = ['foo', 'bar']
bar = foo.deep_copy() 
assert foo == bar
assert ! foo.is(bar)
assert ! foo[0].is(bar[0])

如果您想要基于某种运行时上下文的深度复制语义,或者类别(再次参见groovy 文档):

import groovy.lang.Category

@Category(ArrayList)
class ArrayListDeepCopy {
   def clone() {
      collect { it.getClass().newInstance(it) }
   } 
}

use(ArrayListDeepCopy) {
   def foo = ['foo', 'bar']
   def bar = foo.clone() 
   assert foo == bar
   assert ! foo.is(bar)
   assert ! foo[0].is(bar[0]) // deep copying semantics
}

def foo = ['foo', 'bar']
def bar = foo.clone() 
assert foo == bar
assert ! foo.is(bar)
assert foo[0].is(bar[0]) // back to shallow clone
于 2016-04-28T02:01:50.727 回答
10

对于 Json (LazyMap) 这对我来说很重要

copyOfMap = new HashMap<>()
originalMap.each { k, v -> copyOfMap.put(k, v) }
copyOfMap = new JsonSlurper().parseText(JsonOutput.toJson(copyOfMap))

编辑:简化:Ed Randall

copyOfMap = new JsonSlurper().parseText(JsonOutput.toJson(originalMap))
于 2018-10-25T11:21:36.307 回答
9

我也遇到了这个问题,我刚刚发现:

deepCopy = evaluate(original.inspect())

尽管我在 Groovy 中编码不到 12 个小时,但我想知道使用evaluate. 此外,上面不处理反斜杠。这:

deepCopy = evaluate(original.inspect().replace('\\','\\\\'))

做。

于 2013-07-30T22:35:24.553 回答
4

恐怕你必须这样做clone。你可以试试Apache Commons Lang SerializationUtils

于 2012-10-31T09:49:20.563 回答