如何在Java中复制对象? [英] How do I copy an object in Java?

查看:119
本文介绍了如何在Java中复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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 I want to change 'dum' without affecting the 'dumtwo'. But the above code 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在 Effective 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中复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆