Mercurial Hosting > luan
comparison core/src/luan/DeepCloner.java @ 171:3dcb0f9bee82
add core component
git-svn-id: https://luan-java.googlecode.com/svn/trunk@172 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Sun, 22 Jun 2014 05:41:22 +0000 |
parents | src/luan/DeepCloner.java@0149bdf98fd8 |
children | 24ede40ee0aa |
comparison
equal
deleted
inserted
replaced
170:7c792a328a83 | 171:3dcb0f9bee82 |
---|---|
1 package luan; | |
2 | |
3 import java.util.Map; | |
4 import java.util.IdentityHashMap; | |
5 | |
6 | |
7 public final class DeepCloner { | |
8 private final Map<Object,Object> cloned = new IdentityHashMap<Object,Object>(); | |
9 | |
10 public <T extends DeepCloneable<T>> T deepClone(T obj) { | |
11 @SuppressWarnings("unchecked") | |
12 T rtn = (T)cloned.get(obj); | |
13 if( rtn == null ) { | |
14 rtn = obj.shallowClone(); | |
15 cloned.put(obj,rtn); | |
16 obj.deepenClone(rtn,this); | |
17 } | |
18 return rtn; | |
19 } | |
20 | |
21 public <T> T[] deepClone(T[] obj) { | |
22 if( obj.length == 0 ) | |
23 return obj; | |
24 @SuppressWarnings("unchecked") | |
25 T[] rtn = (T[])cloned.get(obj); | |
26 if( rtn == null ) { | |
27 rtn = obj.clone(); | |
28 cloned.put(obj,rtn); | |
29 for( int i=0; i<rtn.length; i++ ) { | |
30 @SuppressWarnings("unchecked") | |
31 T t = get(rtn[i]); | |
32 rtn[i] = t; | |
33 } | |
34 } | |
35 return rtn; | |
36 } | |
37 | |
38 public <T> T get(T obj) { | |
39 if( !(obj instanceof DeepCloneable) ) | |
40 return obj; | |
41 @SuppressWarnings("unchecked") | |
42 T dc = (T)deepClone((DeepCloneable)obj); | |
43 return dc; | |
44 } | |
45 } |