Home  >  Article  >  Java  >  Detailed analysis of shallow cloning and deep cloning in java objects (with examples)

Detailed analysis of shallow cloning and deep cloning in java objects (with examples)

不言
不言forward
2018-10-10 11:19:302004browse

This article brings you a detailed analysis of shallow cloning and deep cloning in Java objects (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Introduction:

In the Object base class, there is a method called clone, which generates a clone of an early object. The cloned object is a copy of the original object. Due to the existence of reference types, there is deep cloning. The difference between shallow cloning and shallow cloning is that if there is a reference type attribute in the cloned object, deep cloning will make a complete copy of the attribute, while shallow cloning only copies a reference to the attribute. First, let’s take a look at a few minor problems that are easy to make

The clone method belongs to the Object class, not the Cloneable interface. Cloneable is just a mark interface. The mark interface uses user marks to implement the interface. The class has some kind of The function of interface marking. There are three common marking interfaces: Serializable, Cloneable, and RandomAccess. If the Cloneable interface is not implemented, then calling the clone method will cause a CloneNotSupportedException exception.

The clone method in the Object class is modified with protected, which means that if we do not override this method in the subclass, it will not be accessible outside the subclass, because this protected permission can only be used in the Object. Packages and subclasses can access it, which also verifies the statement that subclasses can make the permission modifier larger when overriding parent class methods, but not smaller.

protected native Object clone() throws CloneNotSupportedException;

Overriding the clone method internally only calls the clone method of the parent class. In fact, it is to expand access rights. Of course, you can change protected to public, and you don’t need to rewrite it if you inherit in the future. Of course, it is only the clone function for shallow cloning, and deep cloning needs to be modified.

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

If the attribute is String, and String is also a class, is String a reference type? String behaves like a basic type. The bottom line is that String cannot be changed. After cloning, the two references point to the same String. However, when one of them is modified, the value of the String is not changed, but a new string is generated. The modified reference points to the new string. The appearance looks just like the basic type.

Shallow clone: ​​

Shallow clone means that reference type attributes cannot be completely copied. The class User contains the grade attribute Mark. Mark is composed of Chinese, math, etc. Examples of shallow clone failures

class Mark{
    private int chinese;
    private int math;
    public Mark(int chinese, int math) {
        this.chinese = chinese;
        this.math = math;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public void setMath(int math) {
        this.math = math;
    }

    @Override
    public String toString() {
        return "Mark{" +
                "chinese=" + chinese +
                ", math=" + math +
                '}';
    }
}
public class User implements Cloneable{
    private String name;
    private int age;
    private Mark mark;

    public User(String name, int age,Mark mark) {
        this.name = name;
        this.age = age;
        this.mark = mark;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", mark=" + mark +
                '}';
    }

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

    public static void main(String[] args) throws CloneNotSupportedException {
        Mark mark = new Mark(100,99);
        User user = new User("user",22,mark);
        User userClone = (User) user.clone();
        System.out.println("原user:"+user);
        System.out.println("克隆的user:"+userClone);
        //修改引用类型的mark属性
        user.mark.setMath(60);
        System.out.println("修改后的原user:"+user);
        System.out.println("修改后的克隆user:"+userClone);
    }
}

The output result is:

Original user: User{name='user', age=22, mark=Mark{chinese=100, math=99}}
Clone user: User{name='user', age=22, mark=Mark{chinese=100, math=99}}
Modified original user: User{name='user', age=22, mark= Mark{chinese=100, math=60}}
Modified clone user: User{name='user', age=22, mark=Mark{chinese=100, math=60}}

It is clear that after the user's mark is changed, the cloned user is also modified. And if you want not to be affected, you need deep cloning.

Deep cloning:

Method 1: Nested calling of clone function

Since the reference type cannot be completely cloned, the reference type also implements the Cloneable interface and rewrites the clone method. , the clone method in the User class calls the clone method of the attribute, that is, the nested call of the method

class Mark implements Cloneable{
    private int chinese;
    private int math;
    public Mark(int chinese, int math) {
        this.chinese = chinese;
        this.math = math;
    }
    public void setChinese(int chinese) {
        this.chinese = chinese;
    }
    public void setMath(int math) {
        this.math = math;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    @Override
    public String toString() {
        return "Mark{" +
                "chinese=" + chinese +
                ", math=" + math +
                '}';
    }
}
public class User implements Cloneable{
    private String name;
    private int age;
    private Mark mark;

    public User(String name, int age,Mark mark) {
        this.name = name;
        this.age = age;
        this.mark = mark;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", mark=" + mark +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.mark = (Mark) this.mark.clone();
        return user;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Mark mark = new Mark(100,99);
        User user = new User("user",22,mark);
        User userClone = (User) user.clone();
        System.out.println("原user:"+user);
        System.out.println("克隆的user:"+userClone);
        //修改引用类型的mark属性
        user.mark.setMath(60);
        System.out.println("修改后的原user:"+user);
        System.out.println("修改后的克隆user:"+userClone);
    }
}

The output result is:  

  Original user: User{name='user', age =22, mark=Mark{chinese=100, math=99}}
Clone user: User{name='user', age=22, mark=Mark{chinese=100, math=99}}
The modified original user: User{name='user', age=22, mark=Mark{chinese=100, math=60}}
The modified clone user: User{name='user', age =22, mark=Mark{chinese=100, math=99}}

Method 2: Serialization

The previous method is enough to meet our needs, but if the There are many relationships, or some attributes are arrays. Arrays cannot implement the Cloneable interface (we can manually copy the array in the clone method), but we have to write the clone method by hand every time, which is very troublesome, and the serialization method only needs to give each Each class implements a Serializable interface, which is also a mark interface. Finally, the serialization and deserialization operations are used to achieve the purpose of cloning (including copying of arrays). For knowledge about serialization and deserialization, please refer to the next article

import java.io.*;
class Mark implements Serializable {
    private int chinese;
    private int math;
    public Mark(int chinese, int math) {
        this.chinese = chinese;
        this.math = math;
}
    public void setChinese(int chinese) {
        this.chinese = chinese;
    }
    public void setMath(int math) {
        this.math = math;
    }
    @Override
    public String toString() {
        return "Mark{" +
                "chinese=" + chinese +
                ", math=" + math +
                '}';
    }
}
public class User implements Serializable{
    private String name;
    private int age;
    private Mark mark;

    public User(String name, int age,Mark mark) {
        this.name = name;
        this.age = age;
        this.mark = mark;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", mark=" + mark +
                '}';
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Mark mark = new Mark(100,99);
        User user = new User("user",22,mark);

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(user);//序列化
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        User userClone = (User) oi.readObject();//反序列化

        System.out.println("原user:"+user);
        System.out.println("克隆的user:"+userClone);
        user.mark.setMath(59);
        System.out.println("修改后的原user:"+user);
        System.out.println("修改后的克隆user:"+userClone);
    }
}

Output results:

Original user: User{name='user', age=22, mark=Mark{chinese= 100, math=99}}
The cloned user: User{name='user', age=22, mark=Mark{chinese=100, math=99}}
The modified original user: User{ name='user', age=22, mark=Mark{chinese=100, math=60}}
Modified clone user: User{name='user', age=22, mark=Mark{chinese= 100, math=99}}

 Clone with array attributes

import java.io.*;
import java.util.Arrays;

public class User implements Serializable{
    private String name;
    private int age;
    private int[] arr;

    public User(String name, int age, int[] arr) {
        this.name = name;
        this.age = age;
        this.arr = arr;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", arr=" + Arrays.toString(arr) +
                '}';
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        int[] arr = {1,2,3,4,5,6};
        User user = new User("user",22,arr);

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(user);//序列化
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        User userClone = (User) oi.readObject();//反序列化

        System.out.println("原user:"+user);
        System.out.println("克隆的user:"+userClone);
        user.arr[1] = 9;
        System.out.println("修改后的原user:"+user);
        System.out.println("修改后的克隆user:"+userClone);
    }
}

The above is the detailed content of Detailed analysis of shallow cloning and deep cloning in java objects (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete