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 ʻintor
String` 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