Ans: Possibility 1 : Using the shallow Copy
Possibility 2 : Using the Deep Copy
What is Shallow Copy?
Ans: In Shallow Copy, both the original and copied or duplicate objects share the same
references.Example: if the original object have an vector, then the duplicate object will
point to the vector. That means it does not make any new copy of vector.
BUT,we can add a new elements to duplicate object, if required, and that elements are
only visible to the duplicate objects.
Simply, Shallow copy is something, where original and duplicate are just the elements in
the original object.
What is Deep Copy?
Ans: In this the Original and duplicate will have the distinct variable set which are used
by the original set.So modifying one of the variable in the original Object, does not affect
the duplicate Object.
Sounds Good, Then How to Implement the Deep Copy?
Ans: Using Java Object Serialization [ JOS ].
The idea is simple: Write the object to an array using JOS’s
ObjectOutputStream
and then use
ObjectInputStream
to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects.Sample Program:
public class UnoptimizedDeepCopy { /** * Returns a copy of the object, or null if the object cannot * be serialized. */ public static Object copy(Object orig) { Object obj = null; try { // Write the object out to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); // Make an input stream from the byte array and read // a copy of the object back in. ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return obj; } }
No comments:
Post a Comment