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工具类实现;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇凝子潇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值