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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With