|
First we look at the definition of shallow vs. deep copy
Shallow copy: just copy an object, pointing to an array of other objects inside the object exists or reference are not copied
Deep copy: reference object within the object are copied
To better understand the difference between them we assume that an object A, which contains 2 objects Object A1 and A2
When an object A shallow copy, object B but object is obtained A1 and A2 were not copied
A deep copy of the object, while the object B obtained A1 and A2 together with their references are also copied
After understanding the deep copy and shallow copy, let's look at the deep and shallow copy copy Java implementation. The java.lang.Object clone () method before the default is to return a copy of the object. So if you use the clone () method to implement a deep copy, we must () method to achieve the particular clone each object. When the object hierarchy complicated when doing so is not only difficult but also a waste of time and error-prone, especially sometimes you only need a deep copy of the object at the same time you also shallow copy, you will find that writing this clone () method is not really a good solution.
Then in addition to clone () method, we can also how to achieve it? The answer is serialized, implementation steps and the idea is to copy objects into the output byte array, then use ObjectInputStream convert a new object. Here is the code
public static Object copy (Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
ObjectOutputStream out = new ObjectOutputStream (bos);
out.writeObject (oldObj);
out.flush ();
out.close ();
// Retrieve an input stream from the byte array and read
// A copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream (bos.toByteArray ());
ObjectInputStream in = new ObjectInputStream (bis);
obj = in.readObject ();
} Catch (IOException e) {
e.printStackTrace ();
} Catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace ();
}
return obj;
} |
|
|
|