2011-03-29 6 views
2

가능한 중복 :
How do I copy an object in 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/ 페이지 2 코드와 아주 좋은 예를 제공합니다 How-do-make-a-deep-copy-of-object-in-java – Hubbitus

답변

4

.

MultiMap 인스턴스를 명시 적으로 만들고 원본 인스턴스의 내용을 복사해야합니다.

2

x.aMultimapy.a으로 나타냅니다. 하나에 요소를 추가/제거하면 두 요소에 모두 반영됩니다.

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

깊은 사본입니다.

+0

Integer xb는 어떻습니까? 그것은 같은 y.b를 가리키는가 아닌가? – root

+1

예,하지만 '정수'는 변경되지 않으므로 중요하지 않습니다. – SLaks

+0

그러면 x.b에서 변경하면 y.b가 변경되지 않습니다. – root

관련 문제