Deep copy collection in Java

A copy that does not affect the source even if you copy an array or collection in Java and make changes to the destination is called a deep copy.

If you look it up on the net, you can use ʻintorString` as type arguments.

ArrayList myList = new ArrayList<MyObject>( srcList );

It says that you can make a deep copy by doing something like that, but in fact, if the object is stored in the list, it will not be a deep copy! !!

So, simply taking the collection as an argument and doing new is not enough.

To make a deep copy of a collection of objects, etc.

ArrayList<MyObject> myList = new ArrayList<MyObject>(srcList.size());
for (MyObject o : srcList) {
 //Implement either of the following
 o.add(new MyObject(new o)); //Copy constructor
 o.add(o.clone()); //Clonable interface implementation
}

It seems that you have to prepare a copy constructor for the object to be put in the collection, or inherit the clone method. (You can use either method)

About implementing the Cloneable interface: http://qiita.com/SUZUKI_Masaya/items/8da8c0038797f143f5d3

Deep Copying a Collection of Objects Question: http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents

Recommended Posts

Deep copy collection in Java
☾ Java / Collection
[Personal memo] Make a simple deep copy in Java
Java9 collection
About file copy processing in Java
Study Deep Learning from scratch in Java.
Partization in Java
First steps for deep learning in Java
Changes in Java 11
Java Reintroduction-Java Collection
Pi in Java
FizzBuzz in Java
[Java] Collection framework
Deep dive into how HashMap works in Java
I tried to implement deep learning in Java
[Deep Learning from scratch] in Java 3. Neural network
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
Java collection interview questions
NVL-ish guy in Java
Combine arrays in Java
Callable Interface in Java
Comments in Java source
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Getting Started with Java Collection
Try using RocksDB in Java
Copy dependent jars in Gradle 5
Read binary files in Java 1
Avoid Yubaba's error in Java
Get EXIF information in Java
Save Java PDF in Excel
[Neta] Sleep Sort in Java
Edit ini in Java: ini4j
Java history in this world
Let Java segfault in 6 lines
Java parallelization code sample collection