美文网首页
jdk | 深/浅克隆

jdk | 深/浅克隆

作者: 炒面Z | 来源:发表于2020-04-15 18:25 被阅读0次

实现克隆有两种方式

    1. 实现 Cloneable接口 , 利用clone()方法克隆 为浅克隆
  • 2.实现 Serializable 接口,利用IO流克隆为 深克隆

数组无需实现 Cloneable接口,即可调用clone()方法进行克隆

1.浅克隆 + 深克隆

  • 1.1浅克隆 (默认,不推荐使用)

克隆的Person对象中,son对象并没有真正进行克隆,只做内存地址引用.

@Slf4j
@Accessors(chain = true)
@Data
public class Person implements Serializable, Cloneable {
    private static final long serialVersionUID = -3116169725642569977L;

    private String name;
    private int age;
    private Person son;

    /**
     * 默认浅克隆
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }
}
  • 1.2.深克隆 (2种方式,推荐使用IO流方式)
    /**
     * 深度克隆方法一:利用clone()
     * @return
     * @throws CloneNotSupportedException
     */
    public Person deepClone() throws CloneNotSupportedException {
        Person result = (Person) super.clone();
        if (son != null) {
            result.son = (Person) son.clone();
        }
        return result;
    }


    /**
     * 深度克隆方法一:IO流克隆
     *
     * @return
     */
    public Person IOClone() {
        try {
            // 序列化
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            os.writeObject(this);

            // 反序列化
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream is = new ObjectInputStream(bis);
            return (Person) is.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

2. 数组的克隆

一维数组:深克隆;(重新分配空间,并将元素复制过去)
二维数组:浅克隆。(只传递引用)

  • 2.1 数组克隆
    /**
     * 一维数组:深克隆;(重新分配空间,并将元素复制过去)
     * 二维数组:浅克隆。(只传递引用)
     */
    @Test
    public void arrayCloneTest() {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = a.clone();
        log.info("一维数组:深克隆;(重新分配空间,并将元素复制过去)");

        int[][] x = {{1, 2, 3, 4, 5}, {1, 2}};
        int[][] y = x.clone();
        log.info("二维数组:浅克隆。(只传递引用)");
        log.info("浅克隆: x[0] == y[0] -> {}", x[0] == y[0]);
    }
  • 2.2 二位数组如何深度克隆呢?
        // 二位数组如何深度克隆呢
        int[][] y1 = new int[x.length][];
        for (int i = 0; i < x.length; i++) {
            y1[i] = x[i].clone();
        }
        log.info("深克隆: x[0] == y[0] -> {}", x[0] == y1[0]);

相关文章

网友评论

      本文标题:jdk | 深/浅克隆

      本文链接:https://www.haomeiwen.com/subject/luthvhtx.html