Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy contents from object to another without having same object reference, in Java

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 ?

like image 749
Pier-Alexandre Bouchard Avatar asked Sep 23 '26 08:09

Pier-Alexandre Bouchard


1 Answers

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.

like image 80
Dev Avatar answered Sep 26 '26 01:09

Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!