Java | Deep cloning object containing list of other objects

|
| By Webner

Suppose you have a class like this:

public class Student {
    private String name;
    private int rollNumber;
    private int grade;
    private List subjects;
}

This is the Subject class

public class Subject {
    private String sName;
}

You have an object sObj1 of Student class and it also contains a list of subjects assigned to its instance variable of List type – subjects.

Suppose you want to clone sObj1 into sObj2. There are 2 ways – shallow and deep cloning.

Shallow cloning
Shallow cloning will clone only primitives like rollNumber, grade etc. String type variable ‘name’ is already immutable so that is not a problem. But what happens with list – subjects? It does not clone the subjects, instead only a new reference in memory is created which points to same list of subjects.

For shallow cloning just implement Cloneable interface like this:

public class Student implements Cloneable {
    //Shallow Cloning method......................
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

//this is how to do cloning		
sObjt2 = (Student) sObjt1.clone();
Deep cloning
With deep cloning List can also be cloned but we need to write code
for it in the clone method as below:
    public class Subject implements Cloneable {
        private String sName;

        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
public class Student implements Cloneable {
    //Deep Cloning method......................
    public Object clone() throws CloneNotSupportedException {
        Student cloned = (Student) super.clone();
        cloned.setSubjects(Student.cloneList(this.subjects()));

        return cloned;
    }
    public static List cloneList(List list) {
        List clone = new ArrayList(list.size());
        for (Subject item: list) clone.add(item.clone());
        return clone;
    }
}

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *