#copy
#clone
#object
#java

How to copy an object in Java ?

Anonymous

AnonymousJan 07, 2024

In this posts, we will learn How to copy an object in Java ?

There are various ways to copy an object in Java, depending on your needs and the type of object. Here are some typical methods:

Method 1: Shallow Copy

If the object contains only primitive data types or immutable objects, you can perform a shallow copy by simply assigning the object reference to a new variable. Both the original object and the copied object will refer to the same memory location. Any changes made to the object will be reflected in both references.

OriginalObject original = new OriginalObject();
OriginalObject copy = original; // Shallow copy
```

Method 2: Using the clone() method

If the object implements the Cloneable interface, you can use the clone() method to create a copy of the object. However, this approach creates a shallow copy, meaning that the object's reference fields will still refer to the same memory locations as the original object.

OriginalObject original = new OriginalObject();
OriginalObject copy = (OriginalObject) original.clone(); // Clone method
```

Method 3: Deep Copy

If the object contains mutable reference fields, you may need to perform a deep copy to create a completely independent copy of the object, including its referenced objects. In this case, you need to manually create a new object and copy the values from the original object to the new one.

public class OriginalObject implements Cloneable {
    private int value;
    private SomeMutableObject mutableObject;

    // ...

    @Override
    protected Object clone() throws CloneNotSupportedException {
        OriginalObject copy = (OriginalObject) super.clone();
        copy.mutableObject = new SomeMutableObject(this.mutableObject.getValue());
        return copy;
    }
}

// Usage:
OriginalObject original = new OriginalObject();
OriginalObject copy = (OriginalObject) original.clone(); // Deep copy
```

In this example, the `OriginalObject` class implements the `Cloneable` interface and overrides the `clone()` method to perform a deep copy. The `clone()` method creates a new instance of `OriginalObject` and copies the values from the original object, including creating a new instance of the referenced mutable object.

Please be aware that in order to obtain a fully independent copy, you must make sure that all referenced objects are accurately copied when doing a deep copy.

It's important to note that deep copies and object serialisation in Java can also be accomplished by using third-party libraries like Gson or Apache Commons Lang. These libraries offer easy ways to make copies of objects.

Happy Coding! ❤️