zoukankan      html  css  js  c++  java
  • java 深拷贝与浅拷贝

    yls 2019年11月07日

    1. 拷贝分为引用拷贝和对象拷贝
    2. 深拷贝和浅拷贝都属于对象拷贝

    浅拷贝:通过Object默认的clone方法实现

    1. 实现Cloneable接口

      public class Sheep implements Cloneable
      
    2. 重写clone方法

          //默认浅拷贝
              @Override
              protected Object clone() throws CloneNotSupportedException {
                  return super.clone();
              }
      
      

    深拷贝

    方式一

    1. 实现Cloneable接口

      public class Sheep implements Cloneable
      
    2. 重写并修改clone方法

          //深拷贝,方法一
              //使用clone方式,要实现Cloneable接口
              public Object deepClone() throws CloneNotSupportedException{
                  Sheep sheep=(Sheep) super.clone();
                  sheep.setFather((Father) sheep.getFather().clone());
                  return sheep;
              }
      

    方式二:通过序列化的方式

    1. 实现Serializable接口

      //深拷贝,方法二
          //通过序列化的方式,要实现Serializable接口
          public Object deepClone2() throws Exception {
              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
              ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
      
              oos.writeObject(this);
              ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
              return ois.readObject();
          }
      
  • 相关阅读:
    数据库删除Push
    MFC Tab Control控件的详细使用
    mysql char和varchar的长度
    PostgreSQL常用脚本
    Linux常用操作命令
    PostgreSQL杀掉会话
    PostgresSQL备份还原
    Grpc客户端添加请求头(Header)
    Polly重试
    名词探疑3:I18N,L10N,A11Y
  • 原文地址:https://www.cnblogs.com/yloved/p/11821427.html
Copyright © 2011-2022 走看看