考虑下面的代码:
DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the dum
to dumtwo
and change dum
without affecting the dumtwo
.但是上面的代码并没有这样做。当我更改 dum
中的内容时,同样的更改也发生在 dumtwo
中。
我想,当我说 dumtwo = dum
时,Java 只复制引用。那么,有没有办法创建 dum
的新副本并将其分配给 dumtwo
?
原文由 Veera 发布,翻译遵循 CC BY-SA 4.0 许可协议
创建复制构造函数:
每个对象还有一个克隆方法,可以用来复制对象,但不要使用它。创建一个类并执行不正确的克隆方法太容易了。如果您打算这样做,请至少阅读 _Effective Java_ 中 Joshua Bloch 所说的内容。