quarks
quarks

Reputation: 35346

Cloning a Java object

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.

Upvotes: 2

Views: 531

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114817

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.

Upvotes: 2

Odinn
Odinn

Reputation: 808

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);

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22910

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.

Upvotes: 1

Related Questions