Object clone and why
Object clone is the simplest. In terms of memory storage on the heap (excluding internal memory), the clone of object a is to allocate a place on the heap that is as large as the storage space occupied by object a on the heap, then copy the memory content on the heap of a to the allocated memory space.
Let's look at the example.
class User {String name;int age;}class Account implements Cloneable {User user;long balance;@Overridepublic Object clone() throws CloneNotSupportedException {return super.clone();}}
// User. user user = new User (); user. name = "user"; user. age = 20; // account. account account = new Account (); account. user = user; account. balance = 10000; // copy. account copy = (Account) account. clone (); // balance because it is primitive, copy and prototype are equal and independent. Assert. assertEquals (copy. balance, account. balance); copy. balance = 20000; // changing copy does not affect the prototype. Assert. assertTrue (copy. balance! = Account. balance); // because the user is of the reference type, the copy and prototype references are the same. Assert. assertTrue (copy. user = account. user); copy. user. name = "newName"; // The Same Thing is changed. Assert. assertEquals ("newName", account. user. name );
VcHLz + release/release + HTsM/stb3UrdDNtcTE2rK/release + release/ydLUuMSx5Mv8tcTE2rK/release + resume "brush: java; "> class User implements Cloneable {String name; int age; @ Overridepublic Object clone () throws CloneNotSupportedException {return super. clone ();}}
// User. user user = new User (); user. name = "user"; user. age = 20; // copyUser copy = (User) user. clone (); // age because it is primitive, copy and prototype are equal and independent. Assert. assertEquals (copy. age, user. age); copy. age = 30; // changing copy does not affect the prototype. Assert. assertTrue (copy. age! = User. age); // name because it is a reference type, the copy and prototype references are the same. Assert. assertTrue (copy. name = user. name); // String is an unchangeable class. There is no way to change this string through the copy. name operation. // Changing the referenced object does not affect the prototype. Copy. name = "newname"; Assert. assertEquals ("newname", copy. name); Assert. assertEquals ("user", user. name );
It can be seen that when cloning, primitive and immutable object types can be treated similarly.
Why is clone implemented in java?
You may have the following considerations.
1. Efficiency and Simplicity: simply copy the memory of an object on the heap is much more efficient and simple than traversing an object network and then copying the memory depth.
2. Do not impose meaning on other classes. If Cloneable is implemented by A and A reference is directed to B, if the memory is directly copied for deep copy, B also supports Clone, but this is done in A using B, and B does not even know. Destroys B's original interface.
3. the semantics may be damaged. If A implements Cloneable and A reference points to B, B is implemented in singleton mode. If the memory is directly copied for deep copy, the singleton mode of B is destroyed.
4. It is convenient and more flexible. If A references an immutable object, memory deep copy is A waste. Shadow copy gives programmers better flexibility.
How to clone
Clone trilogy.
1. Implement the Cloneable interface.
2. Call super. clone to get an object. If there is no problem with the clone Implementation of the parent class, all fields defined by the parent class have been cloned in the memory storage of the object, the primitive and immutable type references in this class are also cloned, And the mutable type references are all shortest copies.
3. Point the reference of the shortest copy to the new clone of the prototype object.
Here is an example.
class User implements Cloneable {String name;int age;@Overridepublic User clone() throws CloneNotSupportedException {return (User) super.clone();}}class Account implements Cloneable {User user;long balance;@Overridepublic Account clone() throws CloneNotSupportedException {Account account = null;account = (Account) super.clone();if (user != null) {account.user = user.clone();}return account;}}
The system's default implementation has helped us do a lot of things.
But it also has shortcomings.
1. Manually maintain the clone call chain. This problem is not big, and programmers have the responsibility to do well.
2. If the field of the class is a final variable class, it will not work. Step 3 of the trilogy cannot be done.
Consider the attitude of a class to clone as follows.
1. Public support: Well, follow the clone trilogy. The premise is that the parent class supports (public or silently ).
2 silently supported: Cloneable interface is not implemented, but the correct protected clone implementation is provided in the class. In this way, this class does not support clone, but its subclass will not be blocked if it is to be supported.
3 not supported: Well, to clarify this purpose, provide a clone Implementation of protected that throws a CloneNotSupportedException exception.
4. Support: This class can store instances of other classes. This class is supported if other classes are supported. If other classes are not supported, this class cannot be used, but not supported.
Other options
You can use a prototype constructor or a static copy method to manually create a copy of an object.
The advantage is that the use of this method is not affected even if the field of the class is final. The downside is that all primitive assignments must be maintained by yourself.
Comparison with Serializable
Serializable can also be used to clone objects. However:
Cloneable is designed for clone. Although it has some disadvantages, it is more appropriate to use it for clone if it can be cloned. If not, use a prototype to construct a function, or use a static copy method.
If Serializable creates a clone, too many other things are added, increasing complexity.
1. All related classes must support Serializable. This is more workload than Cloneable.
2 Serializable adds more meaning. In addition to providing a method to create a Clone using Serializable, this class also adds other public APIs. If a class implements Serializable, its binary format is already a part of its API, which is not convenient for future internal changes to the class.
3. When the class is cloned using Serializable, if the user saves an old version of the object in binary format, this class is upgraded, and the user deserializes the object using the new version of the class, then, the object is called to clone with Serializable. This introduces the compatibility of the class version for a clone method. Not cost-effective.
Performance
It is undeniable that the JVM is getting faster and faster.
However, the default native implementation of the system is still quite fast.
Clone an int array with 100 elements. The system's default clone method is about twice faster than the static copy method.