【问题标题】:Java Deep Cloning an object that contain an ArrayList [duplicate]Java深度克隆包含ArrayList的对象[重复]
【发布时间】:2013-06-29 23:11:13
【问题描述】:

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

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();

【问题讨论】:

  • 您不是深度克隆,对于深度克隆,您必须迭代所有数组列表,并且 Objt 应该在克隆方法中进行深度克隆,也许您可​​以将它们序列化并反序列化您获得深度复制

标签: java object arraylist clone


【解决方案1】:

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

@zerocool 答案无效,因为没有克隆 ArrayList 中包含的对象。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2015-01-08
    相关资源
    最近更新 更多