Mercurial Hosting > luan
diff src/luan/LuanCloner.java @ 781:fbbdd369a13a
rename DeepCloner to LuanCloner
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 29 Aug 2016 22:49:32 -0600 |
parents | src/luan/DeepCloner.java@1a68fc55a80c |
children | 655280eab1e2 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/LuanCloner.java Mon Aug 29 22:49:32 2016 -0600 @@ -0,0 +1,60 @@ +package luan; + +import java.util.Map; +import java.util.HashMap; +import java.util.IdentityHashMap; + + +public final class LuanCloner { + private final Map cloned = new IdentityHashMap(); + + public LuanCloneable deepClone(LuanCloneable obj) { + if( obj==null ) + return null; + LuanCloneable rtn = (LuanCloneable)cloned.get(obj); + if( rtn == null ) { + rtn = obj.shallowClone(); + cloned.put(obj,rtn); + obj.deepenClone(rtn,this); + } + return rtn; + } + + public Object[] deepClone(Object[] obj) { + if( obj.length == 0 ) + return obj; + Object[] rtn = (Object[])cloned.get(obj); + if( rtn == null ) { + rtn = obj.clone(); + cloned.put(obj,rtn); + for( int i=0; i<rtn.length; i++ ) { + rtn[i] = get(rtn[i]); + } + } + return rtn; + } + + public Map deepClone(Map obj) { + if( !obj.getClass().equals(HashMap.class) ) + throw new RuntimeException("can only clone HashMap"); + Map rtn = (Map)cloned.get(obj); + if( rtn == null ) { + rtn = new HashMap(); + for( Object stupid : obj.entrySet() ) { + Map.Entry entry = (Map.Entry)stupid; + rtn.put( get(entry.getKey()), get(entry.getValue()) ); + } + } + return rtn; + } + + public Object get(Object obj) { + if( obj instanceof LuanCloneable ) + return deepClone((LuanCloneable)obj); + if( obj instanceof Object[] ) + return deepClone((Object[])obj); + if( obj instanceof Map ) + return deepClone((Map)obj); + return obj; + } +}