2

I found this answer about cloning java objects. However, with the approach in the accepted answer there, is the cloned object is totally a new instance? I mean not really a linked copy?

I am asking this because the java object I need to clone is a "global object" which gets updated at some point in time. And at some point in time I need to "snapshot" the object and essentially put than on a HashMap.

Community
  • 1
  • 1
quarks
  • 33,478
  • 73
  • 290
  • 513
  • Define what exactly you mean by a "linked copy". – NPE Feb 29 '12 at 08:42
  • I mean, at a high-level linked copy, copies which have different instance but when I change the source the copies change. – quarks Feb 29 '12 at 08:52
  • I think the correct term was "Shallow copies", so is the accepted answer on the post linked in my question is a shallow copy. That's what I mean. – quarks Feb 29 '12 at 08:58
  • 1
    If you need all instances to share state, why have more than one instance? – McDowell Feb 29 '12 at 08:58

3 Answers3

2

The accepted answer in the other question briefly explains the copy constructor and, yes, this pattern will create new objects and can (should!) be used to create those snapshots.

The new object will get the current state of the original object. Which is easy for strings and java primitives.

For objects, it's more tricky: the current state is a pointer to another object, and if this other objects changes, the changes will be reflected in your snapshot. If you need to avoid that, then you have to clone these objects too (deep cloning).

The "Problem" with cloning via copy constructor: the cloneable classes need to provide such a constructor. Easy, if you own the source code - then you can implement it yourself. Otherwise you may have to play with Reflection API and implement a clone factory which would be at least ... err, challenging.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
1

You have to determine how deep you want to clone. Anyway this is not really cloning. It is better to implements Clonable and deep copy any relevant field. Other field objects can be referenced.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • I just need to make sure that the objects in the HashMap field in the source object is copied to the cloned object. – quarks Feb 29 '12 at 08:50
1

You can use a copy constructor to create a clone of the object in a temp variable.

public class foo {
    private int i = 0;

    public foo() { this.i = 5; }
    public foo(foo orig) { this.i = orig.getI(); }

    public getI() { return this.i; }
}

And you use it like:

foo a = new foo();
foo b = new foo(a);
Odinn
  • 808
  • 5
  • 23
  • With this approach I will need to type every field to be copied in the copy constructor. Like if I have a hundred field then I will need to copy each one manually? – quarks Feb 29 '12 at 08:51
  • Yes, I have tested it and Java does not provide default copy constructors. – Odinn Feb 29 '12 at 08:59