import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class TestDeepCopy {
    
    /**
     * ディープコピーの動作確認を行います。
     * @param args
     */
    public static void main(String[] args) {

        HashMap<String, String> mapA_1 = new HashMap<String, String>();
        mapA_1.put("Aitem1", "A1");
        mapA_1.put("Aitem2", "A2");
        mapA_1.put("Aitem3", "A3");
        mapA_1.put("Aitem4", "A4");
        mapA_1.put("Aitem5", "A5");
        
        HashMap<String, String> mapA_2 = new HashMap<String, String>();
        mapA_2.put("Aitem1", "A1-2");
        mapA_2.put("Aitem2", "A2-2");
        mapA_2.put("Aitem3", "A3-2");
        
        // コピー元のデータをセット
        ArrayList<HashMap<String, String>> src = new ArrayList<HashMap<String, String>>();
        src.add(mapA_1);
        
        //元の状態を表示します。
        System.out.println("src:"+src);

        ArrayList<HashMap<String, String>> dst = new ArrayList<HashMap<String, String>>();
        
        //★シャローコピー
        //dst = (ArrayList<HashMap<String, String>>)src.clone();
        
        //★ディープコピー
        dst = (ArrayList<HashMap<String, String>>)deepCopy(src);

        // mapA_1の中身をmapA_2で上書きする
         dst.get(0).putAll(mapA_2);

        System.out.println("src:"+src);
        System.out.println("dst:"+dst);
    }
    
    /**
     * ディープコピーします
     * @param obj コピー元オブジェクト
     * @return コピーオブジェクト
     */
    public static Object deepCopy(Object obj) {
        
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Object rtn = null;
        try {
            
            //オブジェクトをバイト配列に変換
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            
            //バイト列をオブジェクトに再変換
            ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
            rtn = ois.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if( oos != null ) {
                    oos.close();
                }
                if( ois != null ) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rtn;
    }
    
}