2011-03-29 43 views
2

可能重複:
How do I copy an object in Java?如何在java中深度複製對象?

它是確定做這樣的java嗎?

public class CacheTree { 

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

     public void copy(CacheTree anotherObj) { 
      this.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 ? 
} 
+0

http://stackoverflow.com/questions/64036/你怎麼做一個在java中的對象的深拷貝 – Hubbitus 2012-05-03 17:35:49

回答

4

這不是一個副本—兩個對象仍然是指在同一個地圖。

您需要明確創建一個新的MultiMap實例並複製原始實例的內容。

2

x.a將指向相同的Multimap作爲y.a - 如果您添加/刪除元素到一個它將反映在兩個。

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

這是一個深層複製。

+0

整數xb怎麼樣?它是否指相同的y.b或不? – root 2011-03-29 23:16:45

+1

是的,但'整數'是不可變的,所以沒關係。 – SLaks 2011-03-29 23:19:30

+0

所以你的意思是如果我在x.b中進行更改,這不會改變y.b? – root 2011-03-29 23:21:04