Mercurial Hosting > luan
comparison src/luan/DeepCloner.java @ 775:1a68fc55a80c
simplify dir structure
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 26 Aug 2016 14:36:40 -0600 |
parents | core/src/luan/DeepCloner.java@c6bcb8859b93 |
children |
comparison
equal
deleted
inserted
replaced
774:3e30cf310e56 | 775:1a68fc55a80c |
---|---|
1 package luan; | |
2 | |
3 import java.util.Map; | |
4 import java.util.HashMap; | |
5 import java.util.IdentityHashMap; | |
6 | |
7 | |
8 public final class DeepCloner { | |
9 private final Map cloned = new IdentityHashMap(); | |
10 | |
11 public DeepCloneable deepClone(DeepCloneable obj) { | |
12 if( obj==null ) | |
13 return null; | |
14 DeepCloneable rtn = (DeepCloneable)cloned.get(obj); | |
15 if( rtn == null ) { | |
16 rtn = obj.shallowClone(); | |
17 cloned.put(obj,rtn); | |
18 obj.deepenClone(rtn,this); | |
19 } | |
20 return rtn; | |
21 } | |
22 | |
23 public Object[] deepClone(Object[] obj) { | |
24 if( obj.length == 0 ) | |
25 return obj; | |
26 Object[] rtn = (Object[])cloned.get(obj); | |
27 if( rtn == null ) { | |
28 rtn = obj.clone(); | |
29 cloned.put(obj,rtn); | |
30 for( int i=0; i<rtn.length; i++ ) { | |
31 rtn[i] = get(rtn[i]); | |
32 } | |
33 } | |
34 return rtn; | |
35 } | |
36 | |
37 public Map deepClone(Map obj) { | |
38 if( !obj.getClass().equals(HashMap.class) ) | |
39 throw new RuntimeException("can only clone HashMap"); | |
40 Map rtn = (Map)cloned.get(obj); | |
41 if( rtn == null ) { | |
42 rtn = new HashMap(); | |
43 for( Object stupid : obj.entrySet() ) { | |
44 Map.Entry entry = (Map.Entry)stupid; | |
45 rtn.put( get(entry.getKey()), get(entry.getValue()) ); | |
46 } | |
47 } | |
48 return rtn; | |
49 } | |
50 | |
51 public Object get(Object obj) { | |
52 if( obj instanceof DeepCloneable ) | |
53 return deepClone((DeepCloneable)obj); | |
54 if( obj instanceof Object[] ) | |
55 return deepClone((Object[])obj); | |
56 if( obj instanceof Map ) | |
57 return deepClone((Map)obj); | |
58 return obj; | |
59 } | |
60 } |