2015年7月15日 星期三

[ 常見問題 ] Deep copy Map in Groovy

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:
  1. // standard deep copy implementation  
  2. def deepcopy(orig) {  
  3.     def bos = new ByteArrayOutputStream()  
  4.     def oos = new ObjectOutputStream(bos)  
  5.     oos.writeObject(orig); oos.flush()  
  6.     def bin = new ByteArrayInputStream(bos.toByteArray())  
  7.     def ois = new ObjectInputStream(bin)  
  8.     return ois.readObject()  
  9. }  
One testing sample code as below:
  1. def deepcopy(orig) {  
  2.     def bos = new ByteArrayOutputStream()  
  3.     def oos = new ObjectOutputStream(bos)  
  4.     oos.writeObject(orig); oos.flush()  
  5.     def bin = new ByteArrayInputStream(bos.toByteArray())  
  6.     def ois = new ObjectInputStream(bin)  
  7.     return ois.readObject()  
  8. }  
  9.   
  10. def map1 = ['name':'john''age':20]  
  11. printf("Original map1=%s\n", map1)  
  12. def map2 = map1  
  13. map2['name']='bob'  
  14. printf("map2=%s\n", map2)  
  15. printf("map1=%s\n", map1)  // map1 will be affected by modification on map2  
  16. def map3 = deepcopy(map1)  
  17. map3['name']='ken'  
  18. printf("map3=%s\n", map3)  
  19. printf("map1=%s\n", map1)  // map1 won't be affected by modification on map3   
Execution result:
Original map1={name=john, age=20}
map2={name=bob, age=20}
map1={name=bob, age=20}
map3={name=ken, age=20}
map1={name=bob, age=20}


Supplement
Java HashMap - deep copy
Take a look at Deep Cloning, on Google Code you can find a library. You can read it on https://github.com/kostaskougios/cloning.

How it works is easy. This can clone any object, and the object doesn't have to implement any interfaces, like serializable.


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...