java shallow and deep copy copy mechanism Explanation

 java shallow copy and deep copy mechanism Detailed - From - https://www.jb51.net/article/106088.htm

Overview:

In Java, the copy is divided into deep and shallow copy copy two kinds. java implements a method called clone in a common super class Object, this method of clone out of the new object shallow copy, and by their clone method is defined as a deep copy.

(A) Object of the clone method

If we new a new object, with a statement to reference it later before a statement with another statement to reference, then the end result is: These two variables declared will point to the same object, a change is all It is changed. If we want to create a copy of an object, the copy is identical various properties and objects, and modify the copy and the original object is no relationship, so this time we will use the clone method.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package Clone;
 
import java.util.Date;
 
/**
  *
  * @author QuinnNorris
  * java中的两种拷贝机制
  */
public class Clone {
 
   /**
    * @param args
    * @throws CloneNotSupportedException
    */
   public static void main(String[] args) throws CloneNotSupportedException {
     // TODO Auto-generated method stub
 
     ClassA valA = new ClassA( 1 , "old" , new Date());
     // 声明一个新的ClassA对象,我们不需要太关注ClassA的功能
     ClassA valB = valA;
     // 将valA引用的对象赋给valB
     valA.setObject( "new" );
     // 更改valA中的值,此时valB也被更改了,因为valA和valB指向同一个对象
 
     valB = valA.clone(); //通过clone方法制造副本
   }
}

ClassA class rewriting part on the clone method:

?
1
2
3
4
5
6
7
8
//需要实现Cloneable接口
public class ClassA implements Cloneable {
 
   public ClassA clone() throws CloneNotSupportedException {
     return (ClassA) super .clone(); //调用父类(Object)的clone方法
   }
 
}

1. How to use the clone method of Object

It was concluded four rules using the clone method, we share it:

  1. To obtain a copy of the object, we can use the clone () method of class Object.
  2. Clone covering the derived class's base class () method, and declared as public.
  3. In the derived class clone () method, call super.clone ().
  4. Implement the Cloneable interface in a derived class.

 2.protected modified clone method

In java.lang.Object, he will clone method is set to protected modification, this is a very special case. The scope is protected: visible + packet inheritable. The reason for this setting, because this method to return the object is cloned, the clone method that is going to clone type is unknown, there is no way to determine the type of the return value, so that future generations can only be achieved naturally it rewrite it , in order to enable future generations to inherit without unduly and open, set for protected type.

3. implement the clone method need to implement Cloneable interface

So when we override the clone method Why go to achieve Cloneable interface it? In fact, Cloneable interface is a java in a marker interface , marking interfaces are those interfaces no methods and properties , they exist just to let everyone know that some of the information , but also with: xxx instanceof the Cloneable when you can be judged. This is Cloneable interface appears to let the designer know the cloning process . If you need to clone an object, but not implemented (in fact, the "realization" with "writing" is more accurate) Cloneable interface that will produce a checked anomaly .

4. implement the clone method needs to call the parent class clone

We aim to achieve exactly the same copy of the object and call a method of this object, we need to use the clone method of the parent class, and so also the parent class, knowing reached the clone method of Object, then the clone method of Object what use is it ? API is this to say:

protected Object clone () throws CloneNotSupportedException 
Creates and returns a copy of this object. 
"Copy" may depend on the precise meaning of the object's class. The purpose of this is, for any object x, 
the expression: x.clone () = x is true,! 
Expression:. X.clone () getClass () == x.getClass () is also true, 
but these not have to meet the requirements. 
Under normal circumstances: 
. X.clone () the equals (the X-) is true, but it is not necessary to meet the requirements. 
By convention, the returned object should be obtained by calling super.clone. 
If a class and all its superclasses (except Object) have to comply with this agreement, the x.clone (). GetClass () == x.getClass ().

API above is the basic explanation on the part of the clone. We can conclude that, as long as reasonable call spuer.clone () it will return an object to be cloned. At runtime, Object of the clone () to identify what you want to copy an object, then the object space allocated for this purpose, and copy objects, the contents of the original objects one by one to the copy space for new objects. In this clone object, all attributes and object attributes are the same cloned, these same properties are divided into two types:

The first: the eight primitive types and immutable objects (such as String) 
second: other objects

For the first, clone method to their value to the value of the original object, without any problems. For the second, clone method simply copy the new object references point to the original object reference point, the second class object is modified two objects. Well, this time it involves the concept of a copy of the shades.

(B) shallow copy

Shallow copy: All variables are copied object contains the same value as the original object, and all the references to other objects still point to the original object. In other words, only a shallow copy copy the object under consideration, but objects it references are not copied .

Such as for example, a class A, class B has another type of variable. When A rewrite clone function call super.clone, the new object is created and the original object class variable of type B is the same, they point to the same type B variable. If variable B in A made changes, the variable B will be modified in the same copy of the new object out.
Remember that a direct call clone method super.clone realize all is shallow copy.

(Iii) a deep copy

Deep copy: all variables are copied objects contain the same value as the original object, removing variables that refer to other objects. Variables that reference other objects will point to the new object is copied, rather than the original objects that are referenced. In other words, deep copy the object to be copied objects referenced are copied again .

In layman's terms, if shallow copy, beginning two lines, if there is a class of other variables in the final, then this will be the last two lines into one common point to this variable, can be operated on him. Deep copy is completely two lines, noninterference in each other, because he has put all the objects inside the variables are all replicated it again.

Deep copy in the code, the need to write multiple clone function call in this class to other classes in the clone process variables.

(Iv) deep copy serialization

In the framework, we found that sometimes did not override the clone method, then we need to copy an object in time is how to operate it? The answer is that we often use the serialization method to achieve Serializable interface.

To look for other ways to replace a deep copy is compelling circumstances, if the traditional deep copy, do you copy an object to which the chase when many layers to complete copies of all object variables Why? Putting aside the time to do so consuming, just write code will be daunting. Deep copy serialization is such a relatively simple method.

The objects written to the stream is in the process of serialization (Serilization) process, but Java programmers circles and very aptly called "frozen" or "pickled vegetables (picking)" process; and the object is read from the stream out of parallelization (deserialization) process is called "thaw" or "back fresh (depicking)" process. It should be noted that the stream is written in a copy of the object, and the original object still exists in the JVM inside, so "into pickled pickles" is just a copy of the object, Java pickles can also back fresh.

The above is the online professional explanation, I'm not here to trespass. Deep copy an object in the Java language, often the first object that implements the Serializable interface, then the object (really just a copy of the object) is written in a stream (pickled into a pickle), and then read from the stream (the pickles back fresh), we can reconstruct the object.

?
1
2
3
4
5
6
7
8
9
10
11
public Object deepClone()
{
  //写入对象
  ByteArrayOutoutStream bo= new ByteArrayOutputStream();
  ObjectOutputStream oo= new ObjectOutputStream(bo);
  oo.writeObject( this );
  //读取对象
  ByteArrayInputStream bi= new ByteArrayInputStream(bo.toByteArray());
  ObjectInputStream oi= new ObjectInputStream(bi);
  return (oi.readObject());
}

Although this academic code looks complicated, but in fact the object into the stream, a chance. Compared analysis to determine countless clone, this simply could not be easier. This assumes that all objects and internal object references to objects are serializable, otherwise, you need to carefully examine whether those non-serialized object is set to transient.

transient:一个对象只要实现了Serilizable接口,这个对象就可以被序列化(序列化是指将java代码以字节序列的形式写出,即我们上面代码前三行写入对象),Java的这种序列化模式为开发者提供了很多便利,可以不必关系具体序列化的过程,只要这个类实现了Serilizable接口,这个的所有属性和方法都会自动序列化。但是有种情况是有些属性是不需要序列号的,所以就用到这个关键字。只需要实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。

Guess you like

Origin www.cnblogs.com/zhangfengshi/p/11122335.html