Java
Deep Cloning
Object Copying
Serialization
Programming Techniques

Java recommended solution for deep cloning/copying an instance

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Java, creating a deep clone or copy of an instance can be a challenging task, given the constraints of the language's object-oriented nature. A deep clone involves creating a new instance of an object that is completely independent of the original object, with all of its fields and sub-objects also recursively cloned. This is different from a shallow copy, where only the top-level object is copied, and both the original and the copy share common sub-objects. In this article, we'll explore the recommended solutions for deep cloning in Java, along with technical explanations and examples.

Deep Cloning Techniques

Using the Cloneable Interface

While Java's Cloneable interface provides a mechanism for cloning objects via the Object.clone() method, it is often criticized for being broken or inadequate for deep cloning. The Cloneable interface does not define any methods; rather, it acts as a marker to indicate that an object is eligible for cloning. However, the clone() method performs a shallow copy by default, and extending this to a deep copy requires overriding this method.

Pros:

  • Availability in the standard library.

Cons:

  • No automatic deep cloning support.
  • Does not handle references to mutable objects or cyclic dependencies.

Example:

java
1class Person implements Cloneable {
2    private String name;
3    private Address address;
4
5    public Person(String name, Address address) {
6        this.name = name;
7        this.address = address;
8    }
9
10    @Override
11    protected Object clone() throws CloneNotSupportedException {
12        Person cloned = (Person) super.clone();
13        cloned.address = (Address) address.clone(); // Manually clone mutable fields
14        return cloned;
15    }
16}

Serialization

Using Java's serialization mechanism is a straightforward way to achieve deep cloning. By serializing an object to a byte stream and then deserializing it, a complete deep copy is produced.

Pros:

  • Simple to implement for classes that support serialization.
  • Handles complex object graphs including cyclic references.

Cons:

  • Performance overhead due to I/O operations.
  • Requires all objects in the hierarchy to be Serializable.

Example:

java
1import java.io.*;
2
3class Address implements Serializable {
4    private String street;
5
6    public Address(String street) {
7        this.street = street;
8    }
9}
10
11class Person implements Serializable {
12    private String name;
13    private Address address;
14
15    public Person(String name, Address address) {
16        this.name = name;
17        this.address = address;
18    }
19
20    public Person deepCopy() {
21        try {
22            ByteArrayOutputStream bos = new ByteArrayOutputStream();
23            ObjectOutputStream out = new ObjectOutputStream(bos);
24            out.writeObject(this);
25            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
26            ObjectInputStream in = new ObjectInputStream(bis);
27            return (Person) in.readObject();
28        } catch (IOException | ClassNotFoundException e) {
29            throw new RuntimeException("Deep copy failed", e);
30        }
31    }
32}

Apache Commons Lang SerializationUtils

SerializationUtils from Apache Commons Lang provides a utility method for deep cloning via serialization.

Pros:

  • Even simpler implementation than manual serialization.
  • Robust handling of complex objects.

Cons:

  • External library dependency.
  • Serialization overhead.

Example:

java
1import org.apache.commons.lang3.SerializationUtils;
2
3class Person implements Serializable {
4    private String name;
5    private Address address;
6    
7    public Person(String name, Address address) {
8        this.name = name;
9        this.address = address;
10    }
11}
12
13Person original = new Person("John", new Address("123 Elm St."));
14Person clone = SerializationUtils.clone(original);

Using Third-Party Libraries

Libraries such as Kryo and MapStruct offer advanced features and support for deep cloning.

  • Kryo: A fast and efficient object graph serialization framework.
  • MapStruct: Primarily used for mapping between different data types; indirectly useful for cloning.

Pros:

  • High performance with extensive features.
  • Specialized libraries like Kryo efficiently handle complex object graphs.

Cons:

  • Adds external dependencies.
  • Might require learning curve for initial setup and configuration.

Summary Table

MethodDeep Copy SupportPerformanceDependenciesUse Case Potential
CloneableManualHighNo additionalBasic, manual implementation
SerializationYesModerateBuilt-inComplex object graphs
Apache Commons SerializationUtilsYesModerateApache Commons LangSimplified serialization-based cloning
Third-Party LibrariesYesVariableKryo, MapStruct, etc.High performance and complex structures

Conclusion

Choosing the right method for deep cloning in Java depends on the specific requirements of your application, including performance considerations, object graph complexity, and dependency management. While Java lacks built-in deep cloning support, techniques like serialization or third-party libraries provide effective solutions. Understanding the trade-offs and capabilities of each method is crucial for selecting the best approach for your use case.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.