How to implement deep copy and shallow copy in Java?
In Java, deep copy and shallow copy can be implemented in different ways.
- Shallow copy: A shallow copy means that when an object is copied, only the object’s reference is duplicated, not the object itself. When one of the objects is modified, the other object will also be affected.
- Implement shallow copy using the following method:
- Implement the Cloneable interface and override the clone() method. In the clone() method, call the clone() method of the superclass, then return the copied object.
- Copy the array using the copy method. For example, you can perform a shallow copy of an array using Arrays.copyOf() or System.arraycopy(). For instance, int[] array1 = {1, 2, 3}; int[] array2 = Arrays.copyOf(array1, array1.length);
- Deep copy: A deep copy refers to making a copy of an object by not only replicating the object’s references, but also replicating the object itself and all objects referenced by it. This way, making modifications to the copied object will not affect the original object.
- Achieve deep copy using the following method:
- To achieve deep copy, implement the Serializable interface and utilize serialization and deserialization.
- Make a deep copy using a third-party library, such as SerializationUtils.clone() method in Apache Commons Lang. MyClass copy = SerializationUtils.clone(original);
It is important to note that in order for an object to be copied, one of the following conditions must be met:
- The object implements the Cloneable interface and overrides the clone() method.
- The object implements the Serializable interface.
- Utilize the deep copy method provided by a third-party library.