问题:
Consider the code below: 考虑下面的代码:
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
。 But the code above is not doing that. 但是上面的代码没有这样做。 When I change something in dum
, the same change is happening in dumtwo
also. 当我改变的东西dum
,同一个变化在发生dumtwo
也。
I guess, when I say dumtwo = dum
, Java copies the reference only . 我猜想,当我说dumtwo = dum
,Java 仅复制引用 。 So, is there any way to create a fresh copy of dum
and assign it to dumtwo
? 那么,有什么方法可以创建新的dum
副本并将其分配给dumtwo
吗?
解决方案:
参考一: https://stackoom.com/question/3e4f/如何在Java中复制对象参考二: https://oldbug.net/q/3e4f/How-do-I-copy-an-object-in-Java
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4059403