[Java] deep and shallow copy copy

Java objects copy (Object Copy) refers to all the attributes (member variables) of an object copied to the object class have the same type of another go. For example: If, objects A and B both belong to the class S, having the properties a and b. Then the object A copying operation is assigned to the object B: Ba = Aa; Bb = Ab;

A copy target in the program is common, mainly to part or all of an existing object data multiplexed in the new context.

Copy objects in Java can be divided into: a shallow copy (Shallow Copy), a deep copy (Deep Copy).

Introduce a little foreshadowing knowledge: Java data types are divided into basic data types and reference data types. For both types of data, making an assignment operation, when used as a method parameters or return values, there will be a difference value is transmitted and the reference (address) is transmitted.

Shallow copy (Shallow Copy)

  1. The data type is the basic data type member variable, shallow copy transfer a value directly, i.e. attribute values ​​of the object to the new copy. Because two different data, to which the member variables of an object to be modified value, another copy of the object will not affect the data obtained.

  2. For data type is the type of reference data member variables, such as the member variable is an array, an object such as a class, so shallow copy will be passing references, that is, only the reference value of a member variable (memory address) Copy one for the new object. Because in fact the member variables of the two objects point to the same instance. In this case, in a modification of the object member variables affect the values ​​of the member variables of another object.

Implementation:

    1. Assignment by reference;
    2. Override the clone method;

Deep copy (deep copy)

  1. For deep copy is not only to all the basic data types copy the object, but also as a member variable application all references to types of storage space, and copy objects referenced by each reference type, until all objects in the object reachable.

Implementation:

    1. For each reference object a method override clone
      and the clone method implemented by rewriting the basic idea shallow copy of the same, only the object for each object in each layer in FIG implement Cloneable interface and override the clone method, and finally at the top level call all the clone method override the clone method of class to achieve a deep copy. Simply put: every object in each layer are shallow copy

    2. Object serialization achieved by deep copy
      when the target sequence into a sequence of bytes, the default object referenced object serialization, then to deep copy perfectly achieved by reverse sequence.

Guess you like

Origin www.cnblogs.com/daijux/p/11935668.html