问题描述
考虑下面的代码:
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'
所以,我想将 dum
复制到 dumtwo
并更改 dum
而不影响 dumtwo
.但是上面的代码并没有这样做.当我在 dum
中更改某些内容时,dumtwo
中也会发生相同的更改.
So, I want to copy the dum
to dumtwo
and change dum
without affecting the dumtwo
. But the code above is not doing that. When I change something in dum
, the same change is happening in dumtwo
also.
我想,当我说 dumtwo = dum
时,Java 会复制仅引用.那么,有没有办法创建一个 dum
的新副本并将其分配给 dumtwo
?
I guess, when I say dumtwo = dum
, Java copies the reference only. So, is there any way to create a fresh copy of dum
and assign it to dumtwo
?
推荐答案
创建复制构造函数:
class DummyBean {
private String dummy;
public DummyBean(DummyBean another) {
this.dummy = another.dummy; // you can access
}
}
每个对象都有一个克隆方法,可以用来复制对象,但不要使用它.创建一个类并执行不正确的克隆方法太容易了.如果您打算这样做,请至少阅读 Joshua Bloch 在有效的 Java.
Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.
这篇关于如何在 Java 中复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!