在Groovy深副本地图(Deep copy Map in Groovy)

2019-07-03 11:58发布

我怎么能深层副本地图在Groovy的地图? 地图键是字符串或者整形。 的值是字符串,原始对象或其他的地图,以递归方式。

Answer 1:

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

// 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()
}


Answer 2:

我刚刚打这个问题为好,我只是发现:

deepCopy = evaluate(original.inspect())

虽然我在Groovy中被编码少于12个小时,我不知道是否有可能使用一些信任问题evaluate 。 此外,上述不处理反斜杠。 这个:

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

确实。



Answer 3:

去约深度复制在一个类中的每个部件,所述的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中,类,最后是newInstance方法重载。

更新

我上面的例子是最终的浅拷贝的例子,但我真正的意思是,在一般情况下,你几乎总是要定义自己可靠的深度复制的逻辑,也许使用newInstance()方法,如果克隆( )方法是不够的。 这里有几种方法如何去说:

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)

我用@Canonical为equals()方法和元组构造函数。 见常规文档3.4.2章节,代码生成转换 。

到去深度复制的另一种方法是使用混合类型。 比方说,你想要一个已经存在的类有着深厚的复制功能:

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])

或类别(再次看到了常规DOC )如果你想基于某种运行时环境的深度复制语义:

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


Answer 4:

恐怕你必须这样做的clone方法。 你可以给阿帕奇共享郎SerializationUtils一试



Answer 5:

对于JSON(LazyMap)这个wokred我

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

编辑:通过简化艾德·兰德尔

copyOfMap = new JsonSlurper().parseText(JsonOutput.toJson(originalMap))


文章来源: Deep copy Map in Groovy