If you want to modify an object without changing the caller's object, make a local copy of the object. This is also one of the most common uses for local replicas. If you decide to make a local copy, simply use the Clone () method. Clone is the meaning of "cloning", that is, making exactly the same copy. This method is defined as the "protected" (protected) mode in the underlying class object. However, in any derived class that you want to clone, you must overwrite it with "public" mode. For example, the standard library class vector overrides clone (), so you can Invoke clone () for vector, as follows:
//: Cloning.java//The Clone () operation works for only a few//items in the standard Java library.
Import java.util.*;
class int {private int i;
Public Int (Int II) {i = II}
public void Increment () {i++;}
Public String toString () {return integer.tostring (i);
} public class Cloning {public static void main (string[] args) {vector v = new vector ();
for (int i = 0; i < i++) v.addelement (new int (i));
System.out.println ("V:" + V);
Vector v2 = (vector) v.clone ();
Increment All v2 ' s Elements:for (enumeration e = V2.elements (); E.hasmoreelements ();
) ((INT) e.nextelement ()). Increment ();
If it changed V ' s elements:System.out.println ("V:" + V); }
} ///:~
The Clone () method produces an object that must be immediately redesigned to the correct type. This example indicates that the vector clone () method does not automatically attempt to clone each object contained within the vector-because of the alias problem, the old vector and the vector of the clone contain the same object. We usually called this a "simple copy" or "Shallow copy" because it only duplicates the "surface" part of an object. In addition to this "surface", the actual object includes all objects that the handle points to, and all other objects that the object points to, and so on. This is the origin of the "Object Network" or "Object Networks". If all the nets can be reproduced, they are called "full copy" or "Deep copy".
You can see the results of shallow replication in the output, and note that actions taken on V2 also affect V:
V: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
V: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In general, since it is not possible to guarantee that the vector contains objects that are "can be cloned" (annotation ②), it is best not to attempt to clone those objects.
②: "Can clone" in English speaking is cloneable, please note that the Java library specifically reserved such a keyword.