How do I create a copy of the data type I created in Java?
If I have a class:
public class MyType { private List<Integer> data; private boolean someFlag; public MyType(List<Integer> myData,boolean myFlag) { this.data = myData; this.myFlag = someFlag; } }
Now, if I create a mytype instance, how can I make a deep copy of it? I don't want the new object to point to the old reference, but a new instance
Is this the case where I should implement the clonable interface, or for shallow copy?
I cannot do this:
MyType instance1 = new MyType(someData,false); MyType instance2 = new MyType(instance1.getData(),instance1.getFlag());
I'm worried that the new instance of mytype points to the same reference to its "data" variable So I need to copy it completely
So, if I have an existing object:
MyType someVar = new MyType(someList,false); // Now,I want a copy of someVar,not another variable pointing to the same reference.
Can anyone point me in the right direction?
Solution
First: your code example has some naming problems: myFlag or someflag?
Many developers will abandon clonable and just create a copy constructor for the class when a deep copy is required:
public class MyType { private boolean myFlag; private List<Integer> myList; public MyType(MyType myInstance) { myFlag = myInstance.myFlag; myList = new ArrayList<Integer>(myInstance.myList); } }
Copy constructors are common and can be found in many collection implementations For clear reasons, I prefer them to implement clonable It is also worth noting that even the powerful Joshua Bloch in effective Java (page 61 of the Second Edition) indicates that the copy constructor has many advantages over clone / clone
>They don't rely on risk prone extralingual object creation mechanisms > they don't require that they can't enforce adherence conventions > they don't conflict with the correct use of final Fields > they don't throw unnecessary check exceptions > they don't need a cast
If you don't have his book, go!