我的问题很清楚。复制构造函数是否进行深复制?还是浅拷贝?
这是我遇到的情况:
我正在制作一个节点编辑器应用程序。我有一个抽象 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);
}
但运气不佳。它似乎创建了浅拷贝而不是深拷贝。当我添加第一个节点时,它看起来很好。但是,当添加相同类型的第二个节点时,第一个节点将从那里消失并重新出现在新位置。这是否意味着这是在进行浅复制。如果可以,如何实现深拷贝?
最佳答案
首先,Java中默认没有复制构造函数这样的东西。有一个 Cloneable
接口(interface)和 clone()
方法。但该方法默认会进行浅复制。
您的代码集链接到两个对象的属性 location
中相同的 Point2D
对象引用。您需要创建 Point2D
对象的新实例并在新对象中使用它。
关于java - 复制构造函数是否会进行浅复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52386697/