This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

How do I copy objects in Java?

Consider the following code:

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'
Copy the code

Therefore, I want to copy Dum to Dumtwo and change Dum without affecting Dumtwo. But the code above doesn’t do that. When I change Dum, the same change happens to Dumtwo.

I think, when I say dumtwo = dum, Java just copies references. So, is there any way to create a new copy of Dum and assign it to Dumtwo?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Create a copy constructor:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}
Copy the code

Each object has a clone method that you can use to copy objects, but don’t use it. It’s too easy to create classes and perform incorrect cloning methods. If you do, at least read what Joshua Bloch has to say in Effective Java.

Answer:

Basic: Object replication in Java.

Let’s assume that an object, obj1, contains two objects, containedObj1 and containedObj2. Enter the picture description here

Shallow table replication: Shallow table replication creates a new table of instance of the same class and copies all fields to the new instance and returns it. Object classes provide a clone method and support for shallow table replication. Enter the picture description here

Deep copy: Deep copy occurs when an object and the object referenced are copied together. The following figure shows obj1 after a deep copy is performed on it. Not only has Obj1 been copied, but the objects contained within it have also been copied. Java Object Serialization can be used to make deep copies. Unfortunately, there are some problems with this approach (detailed example). Enter the picture description here

Possible problems: Clone is difficult to implement correctly. It is best to use defensive copying, copy constructors (such as @egaga reply) or static factory methods.

If you have an object that you know has a common clone() method, but don’t know the type of the object at compile time, you have a problem. Java has an interface called Cloneable. In practice, this interface Cloneable should be implemented if you want to create objects. Object. Clone is protected, so we must override it with a public method to access it.

Another problem arises when we try to make deep copies of complex objects. It is too risky to assume that the methods of all member object variables are also deeply copied. You must control the code in all classes. clone()Copy the code

For example, org.apache.com mons. Lang. SerializationUtils will have to use serialization (source) method for depth of cloning. If we need to clone the Bean, then org.apache.com mons. Beanutils several utility methods (source).

CloneBean Clones the bean based on available property getters and setters even if the bean class itself does not implement Cloneable. CopyProperties copies the property value from the original Bean to the target Bean in all cases where the property name is the same.

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 8…

Author’s advice: all I can think of is light copy and deep copy. The picture is so good that it’s easy to understand.


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️