Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy an object in Java?

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. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwo also.

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?

like image 606
Veera Avatar asked May 15 '09 14:05

Veera


People also ask

How do you copy an object in Java?

In Java, there is no operator to create a copy of an object. Unlike C++, in Java, if we use the assignment operator then it will create a copy of the reference variable and not the object.

Can you copy an object?

There are several ways to copy an object, most commonly by a copy constructor or cloning. Copying is done mostly so the copy can be modified or moved, or the current value preserved. If either of these is unneeded, a reference to the original data is sufficient and more efficient, as no copying occurs.

How do you copy an object in Java 8?

Utilize Object clone() method by calling super. clone() in overridden clone method, then make necessary changes for deep copying of mutable fields. If your class is serializable, you can use serialization for cloning.

What is copy () in Java?

The copy() method of Java Collections class copies all of the elements from one list into another list. In this method, the size of the destination list must be greater than or equal to the size of the source list.


2 Answers

Create a copy constructor:

class DummyBean {   private String dummy;    public DummyBean(DummyBean another) {     this.dummy = another.dummy; // you can access     } } 

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.

like image 153
egaga Avatar answered Oct 02 '22 15:10

egaga


Basic: Object Copying in Java.

Let us Assume an object- obj1, that contains two objects, containedObj1 and containedObj2.
enter image description here

shallow copying:
shallow copying creates a new instance of the same class and copies all the fields to the new instance and returns it. Object class provides a clone method and provides support for the shallow copying.
enter image description here

Deep copying:
A deep copy occurs when an object is copied along with the objects to which it refers. Below image shows obj1 after a deep copy has been performed on it. Not only has obj1 been copied, but the objects contained within it have been copied as well. We can use Java Object Serialization to make a deep copy. Unfortunately, this approach has some problems too(detailed examples).
enter image description here

Possible Problems:
clone is tricky to implement correctly.
It's better to use Defensive copying, copy constructors(as @egaga reply) or static factory methods.

  1. If you have an object, that you know has a public clone() method, but you don’t know the type of the object at compile time, then you have problem. Java has an interface called Cloneable. In practice, we should implement this interface if we want to make an object Cloneable. Object.clone is protected, so we must override it with a public method in order for it to be accessible.
  2. Another problem arises when we try deep copying of a complex object. Assume that the clone() method of all member object variables also does deep copy, this is too risky of an assumption. You must control the code in all classes.

For example org.apache.commons.lang.SerializationUtils will have method for Deep clone using serialization(Source). If we need to clone Bean then there are couple of utility methods in org.apache.commons.beanutils (Source).

  • cloneBean will Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
  • copyProperties will Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
like image 31
Chandra Sekhar Avatar answered Oct 02 '22 14:10

Chandra Sekhar