-1

Possible Duplicate:
Java: recommended solution for deep cloning/copying an instance

Using Java, how to implement deep clone of an object?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

3 Answers3

3

There is a way to implement deep clone is using copy constructor technique.

example in this link

Hope this help.

Nathanphan
  • 947
  • 2
  • 11
  • 23
0

there are 2 types of copy :

  • shallow copy
  • deep copy

shallow copy constructs a new instance of your object, but do not constructs new instance for fields your object might have. deep copy constructs a new instance of your object, and constructs new instance for fields your object might have, fields of these, etc.

You can have a look on clone() method of ArrayList for more details : this is a shallow copy. If you want deep copy, you have to clone each element your list contains.

Tanguy
  • 191
  • 1
  • 6
-1
public class Person {
    private String name;
    private int age;

    // getters and setters.
}

// deep copy:
Person source = new Person("james", 20);
Person dest = new Person();
dest.setName(source.getName());
dest.setAge(source.getAge());
James.Xu
  • 8,249
  • 5
  • 25
  • 36
  • 1
    This will work as age has a primitive type and name has an immutable type, but won't work with higher level object – Tanguy Mar 31 '11 at 06:14
  • yeah, this **deep copy** need to be done recursively if there are another object in **Person**. – James.Xu Mar 31 '11 at 06:15