Groovy中的深拷贝映射

问题描述 投票:16回答:5

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

groovy deep-copy
5个回答
26
投票

一个简单的方法是:

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

6
投票

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

deepCopy = evaluate(original.inspect())

虽然我在Groovy编写的代码不到12小时,但我想知道使用evaluate是否存在一些信任问题。此外,以上不处理反斜杠。这个:

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

确实。


5
投票

要深入复制类中的每个成员,newInstance()存在于Class对象中。例如,

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()方法( )方法是不够的。以下是几种方法:

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()方法和元组ctor。见groovy doc Chapter 3.4.2, Code Generation Transformations

深度复制的另一种方法是使用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 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

4
投票

我担心你必须以clone方式做到这一点。您可以试试Apache Commons Lang SerializationUtils


3
投票

对于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))
© www.soinside.com 2019 - 2024. All rights reserved.