2

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) {
            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 ?
}
icedwater
  • 4,701
  • 3
  • 35
  • 50

3 Answers3

4

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
1

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

kensen john
  • 5,439
  • 5
  • 28
  • 36