开发者

how to deep copy object in java? [duplicate]

开发者 https://www.devze.com 2023-02-20 11:01 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: How do I copy an object in Java?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How do I copy an object in Java?

Is it ok to do like this in java?

public class CacheTree {

    private Multimap<Integer, Integer> a;
    private Integer                    b;

        public void copy(CacheTree anotherObj) {
            th开发者_运维问答is.a = anotherObj.getA();
            this.b = anotherObj.getB();
        }

       public Multimap<Integer, Integer> getA() {
            return a;
       }

       public Integer getB() {
            return b;
       }
}

public void main() {
     CacheTree x = new CacheTree();
     CacheTree y = new CacheTree();

     x.copy(y);      // Is it ok ?
}


That's not a deep copy—both objects still refer to the same map.

You need to explicitly create a new MultiMap instance and copy over the contents from the original instance.


x.a will refer to the same Multimap as y.a - if you add/remove elements to one it'll be reflected in both.

this.a = new Multimap<Integer, Integer>();
this.a.addAll(anotherObj.getA())

That's a deep copy.


See this article, gives a very good example with code in Page 2. It also explains the concept of deep copying in java

http://www.javaworld.com/javaworld/javatips/jw-javatip76.html

0

精彩评论

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