Source From Here
Question
How can I deep copy a map of maps in Groovy? The map keys are Strings or Ints. The values are Strings, Primitive Objects or other maps, in a recursive way.
How-To
An easy way is this:
One testing sample code as below:
Execution result:
Supplement
* Java HashMap - deep copy
Question
How can I deep copy a map of maps in Groovy? The map keys are Strings or Ints. The values are Strings, Primitive Objects or other maps, in a recursive way.
How-To
An easy way is this:
- // standard deep copy implementation
- def deepcopy(orig) {
- def bos = new ByteArrayOutputStream()
- def oos = new ObjectOutputStream(bos)
- oos.writeObject(orig); oos.flush()
- def bin = new ByteArrayInputStream(bos.toByteArray())
- def ois = new ObjectInputStream(bin)
- return ois.readObject()
- }
- def deepcopy(orig) {
- def bos = new ByteArrayOutputStream()
- def oos = new ObjectOutputStream(bos)
- oos.writeObject(orig); oos.flush()
- def bin = new ByteArrayInputStream(bos.toByteArray())
- def ois = new ObjectInputStream(bin)
- return ois.readObject()
- }
- def map1 = ['name':'john', 'age':20]
- printf("Original map1=%s\n", map1)
- def map2 = map1
- map2['name']='bob'
- printf("map2=%s\n", map2)
- printf("map1=%s\n", map1) // map1 will be affected by modification on map2
- def map3 = deepcopy(map1)
- map3['name']='ken'
- printf("map3=%s\n", map3)
- printf("map1=%s\n", map1) // map1 won't be affected by modification on map3
Supplement
* Java HashMap - deep copy
沒有留言:
張貼留言