Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to backup ArrayList in Java?

Tags:

java

arraylist

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.

like image 569
Stella Avatar asked Nov 19 '08 19:11

Stella


People also ask

How do I make a deep copy of an ArrayList?

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.

What is ArrayList backed by?

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.

Can you copy an ArrayList in Java?

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.


1 Answers

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());
like image 189
Paul Tomblin Avatar answered Oct 15 '22 15:10

Paul Tomblin