3

I need to copy two objects (which are both stacks).

I want to copy a temporary object's content into a current object and then clear the temporary object's content.

For example, with a tree, it would be something like:

tree = tempTree;
tempTree.clear();

But, tree reference now points to temptree and if I clear temptree, it will clear also tree. I looked on other posts, they talked about implements clonable or doing a copy constructor and I am sure there is a better way of copying objects in Java.

My objects are by the way Stack objects.

How can I copy contents from object to another without having same object reference ?

Pier-Alexandre Bouchard
  • 5,135
  • 5
  • 37
  • 72

4 Answers4

1

Unfortunately you will have to code this yourself. The good news is that a Stack is a type of List so you can do a make a copy of it quite easily.

Stack stack = ...; //Existing stack
Stack tempStack = new Stack(); 
tempStack.addAll(stack);

Now tempStack and stack refer to the same set of objects in the same order, but can be independently mutated.

Dev
  • 11,919
  • 3
  • 40
  • 53
0

A direct answer: you create a new instance and then you copy or add the contents of an old instance to the new one. This is what helper methods, copy constructors and cloneable implementations also do under the hood, so in the end you would be doing the same thing.

About implementing cloneable, please see this question before actually jumping on implementing it - that is possibly the least recommended approach for the reasons outlined and referenced in that discussion.

Copy constructor would probably be the recommended way of doing it.

Community
  • 1
  • 1
eis
  • 51,991
  • 13
  • 150
  • 199
0

If the copy object will be of the same class type and is serializable, you can also "just" serialize and deserialize it. This way you will not get just a shallow copy but a full tree of new objects. There are some utility classes around that can help with this. Apache commons has one and I'm not 100% sure but i think there is even one in jdk5 directly. I would have to dig it up though.

Martin Frey
  • 10,025
  • 4
  • 25
  • 30
-1

Take a look at Object.clone() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone()

Stack extends Vector which implements cloneable, so you can simply execute:

Stack stackb = stacka.clone(); 
Jivings
  • 22,834
  • 6
  • 60
  • 101
  • 1
    -1, `Object.clone` is broken and only produces a shallow copy; this comment also applies to @roymustang86 – mre Jan 12 '12 at 18:14
  • It isn't stated that the Stack contains complex Objects. No reason that `clone` wouldn't be viable given the information here. – Jivings Jan 12 '12 at 18:17
  • That would also work. But if your Stack contains primitives then `clone` may be easier. – Jivings Jan 12 '12 at 18:22