首页 > 解决方案 > 复制构造函数是否进行浅拷贝?

问题描述

我的问题很清楚。复制构造函数是否进行深层复制?还是浅拷贝?

这是我面临的情况:

我正在制作一个节点编辑器应用程序。我有一个抽象的 Node 类。在那,我有一个名为 Create() 的抽象方法。我也以这种方式在所有子类中覆盖了该方法,

    public Node Create(){
    TestClass theTest = new TestClass();
    theTest.Name = "Test Node";
    theTest.Title = "Default Node";
    theTest.setSize(new Point2D.Float(250,200));
    System.out.print(theTest.getClass());
    return theTest;
}

我认为这应该做一个深拷贝。由于这不起作用,我也尝试了这个。

public Node Create(Point2D location) {
    TestClass theTest = null;
    try {
        theTest = this.getClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

    if (theTest != null) {
        theTest.Name = "The Node";
        theTest.Title = "Defaul Node";
        theTest.setSize((new Point2D.Float(250,200)));
        theTest.Location = location;
    }

    return theTest;
}

然后将所有子类类型添加到列表中,并使用子类创建弹出菜单。用户可以单击它并添加一个新节点。这是添加节点的代码。此方法由 JMenuItem 的 MouseEvent 调用。

private void addNode(Node node){
    Node newNode = node.Create(locationPersistence);
    nodes.add(newNode);
}

但没有运气。它似乎创建了浅拷贝而不是深拷贝。当我添加第一个节点时,它看起来很好。但是当添加第二个相同类型的节点时,第一个节点会从那里消失并重新出现在新的位置。这是否意味着这是一个浅拷贝。如果是这样,如何实现深拷贝?

标签: javadeep-copy

解决方案


首先,默认情况下,Java 中没有复制构造函数之类的东西。有Cloneable接口和clone()方法。但默认情况下,该方法会进行浅拷贝。

您的代码集链接到两个对象的属性中的相同Point2D对象引用location。您需要创建对象的新实例Point2D并在新对象中使用它。


推荐阅读