java 深克隆與淺克隆的區別, 以及它實現方式幾種方式

淺克隆(Shadow Clone):

把原型對象中成員變量爲值類型的屬性都複製給克隆對象,

把原型對象中成員變量爲引用類型的引用地址也複製給克隆對象, 即 原型對象彙總如果有成員變量爲引用對象,則此引用對象的地址是共享給原型對象的和克隆對象的

  

public class ShadowCloneTest {

    public static void main(String[] args) throws  Exception {

        People p = new People(1,"哈哈");

        People clone = (People) p.clone();

        System.out.println(clone);


    }

    /**
     * 1. 實現Cloneable 接口
     * 2. 重寫 clone 方法
     */
    static class People implements Cloneable {

        private Integer id;

        private  String name;

        public People(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "People{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

}

輸出結果: People{id=1, name='哈哈'}

 

 /**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. The general
     * intent is that, for any object {@code x}, the expression:
     * <blockquote>
     * <pre>
     * x.clone() != x</pre></blockquote>
     * will be true, and that the expression:
     * <blockquote>
     * <pre>
     * x.clone().getClass() == x.getClass()</pre></blockquote>
     * will be {@code true}, but these are not absolute requirements.
     * While it is typically the case that:
     * <blockquote>
     * <pre>
     * x.clone().equals(x)</pre></blockquote>
     * will be {@code true}, this is not an absolute requirement.
     * <p>
     * By convention, the returned object should be obtained by calling
     * {@code super.clone}.  If a class and all of its superclasses (except
     * {@code Object}) obey this convention, it will be the case that
     * {@code x.clone().getClass() == x.getClass()}.
     * <p>
     * By convention, the object returned by this method should be independent
     * of this object (which is being cloned).  To achieve this independence,
     * it may be necessary to modify one or more fields of the object returned
     * by {@code super.clone} before returning it.  Typically, this means
     * copying any mutable objects that comprise the internal "deep structure"
     * of the object being cloned and replacing the references to these
     * objects with references to the copies.  If a class contains only
     * primitive fields or references to immutable objects, then it is usually
     * the case that no fields in the object returned by {@code super.clone}
     * need to be modified.
     * <p>
     * The method {@code clone} for class {@code Object} performs a
     * specific cloning operation. First, if the class of this object does
     * not implement the interface {@code Cloneable}, then a
     * {@code CloneNotSupportedException} is thrown. Note that all arrays
     * are considered to implement the interface {@code Cloneable} and that
     * the return type of the {@code clone} method of an array type {@code T[]}
     * is {@code T[]} where T is any reference or primitive type.
     * Otherwise, this method creates a new instance of the class of this
     * object and initializes all its fields with exactly the contents of
     * the corresponding fields of this object, as if by assignment; the
     * contents of the fields are not themselves cloned. Thus, this method
     * performs a "shallow copy" of this object, not a "deep copy" operation.
     * <p>
     * The class {@code Object} does not itself implement the interface
     * {@code Cloneable}, so calling the {@code clone} method on an object
     * whose class is {@code Object} will result in throwing an
     * exception at run time.
     *
     * @return     a clone of this instance.
     * @throws  CloneNotSupportedException  if the object's class does not
     *               support the {@code Cloneable} interface. Subclasses
     *               that override the {@code clone} method can also
     *               throw this exception to indicate that an instance cannot
     *               be cloned.
     * @see java.lang.Cloneable
     */
    protected native Object clone() throws CloneNotSupportedException;

通過 Object#clone() 方法 源碼可以知道:

1.對於所有對象來說, x.clone() != x 返回true,因爲克隆對象和原對象不是同一個對象

2.對於所有對象來說,x.clone().getClass() == x.getClass() 返回true,因爲克隆對象與原對象的類型是一樣的

3.對於所有對象來說 ,x.clone().equals(x) 返回true,因爲equals比較時,它們的值都相等

4. clone() 方法使用native修飾的本地方法,因此執行性能會很高,返回類型爲Object,因此在調用克隆之後要把對象強轉爲目標類型纔行

 

 

深克隆(Deep Clone): 

將原型對象中的所有類型,無論是值類型還是引用類型,都複製一份給克隆對象, 即 深克隆會把原型對象和原型對象所引用的對象,都複製一份給克隆對象

實現深克隆的幾種方式:

1.所有對象都實現克隆方法;

2.通過構造方法實現深克隆;

3.使用JDK自帶的字節流實現深克隆;

4.使用第三方工具實現深克隆,比如ApacheCommonsLang;

5.使用JSON工具類實現;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章