开发者

How to implement deep clone of an object [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Java: recommended solution for d开发者_StackOverflow社区eep cloning/copying an instance

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


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

example in this link

Hope this help.


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.


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜