I have some data stored as ArrayList
. And when I want to backup this data,java bounds two objects forever. Which means when I change values in data ArrayList
this changes come to backup. I tried to copy values from data separately to backup in the loop, tried to use method data.clone()
— nothing helps.
To create a true deep copy of ArrayList, we should create a new ArrayList and copy all the cloned elements to new ArrayList one by one and we should also clone Student object properly. To create deep copy of Student class, we can divide its class members to mutable and immutable types.
ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance as it involves new array and copying content from an old array to a new array. It calls the native implemented method System.
The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.
Your question isn't very clear. If you clone() an ArrayList, the clone will not be modified if you change the contents of the original (ie if you add or remove elements) but it's a "shallow copy" so if you change the actual objects in the original they will also be changed in the clone.
If you want to make a "deep copy", so that changes to the actual objects will not affect the backups of them in the clone, then you need to create a new ArrayList and then go through the original one and for each element, clone it into the new one. As in
ArrayList backup = new ArrayList();
for (Object obj : data)
backup.add(obj.clone());
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