Java深度克隆包含ArrayList的对象

时间:2013-07-02 14:18:39

标签: java object arraylist clone

您好我必须深度克隆包含数组列表的对象。

public class Objct1 implements Cloneable {
    ArrayList<Objt> o = new ArrayList();

    public Object1() {
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            // This should never happen
            throw new InternalError(e.toString());
        }
    }
}

public class Objt implements Cloneable {
    private int ca;

    /**
     * @return the x
     */
    public int getCa() {
        return x;
    }

    /**
     * @param x the x to set
     */
    public void setCa(int ca) {
        this.ca = ca;
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            // This should never happen
            throw new InternalError(e.toString());
        }
    }
}

我正在尝试克隆此示例中的Objct1

Objct1 a = new Objct1 ();

arryOfObjct1[count] = (Objct1) a.clone();

1 个答案:

答案 0 :(得分:1)

重复的: How to clone ArrayList and also clone its contents?

@zerocool答案无效,因为它不是克隆ArrayList中包含的对象。