One, foreword

Copy the word must be familiar to everyone, in the work often need to copy a document as a copy. The benefits of copy are also obvious, compared to new, can save a lot of work. In Java, the concept of copy also exists, and the purpose of copy is to save the overhead of creating objects.

The Object class has a clone() method that looks like this:

protected native Object clone(a) throws CloneNotSupportedException;
Copy the code
  1. The method byprotectedAll classes in Java inherit by defaultObjectClass, overloadedclone()Method to ensure that all other classes can be called properly, the modifier needs to be changed topublic.
  2. The method is anativeMethods,nativeThe decorated methods are actually implemented by non-Java code and are more efficient than normal Java methods.
  3. The return value of this method isObjectObject, so we need to force the type we need.
  4. The method throws oneCloneNotSupportedExceptionException, meaning that copy is not supported, we need to implementCloneableInterface, this class supports copying.

Create two new entity classes, Dept, and User. User relies on Dept.

Dept:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {

    private int deptNo;
    private String name;
}
Copy the code

The User class:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int age;
    private String name;
    private Dept dept;
}
Copy the code

Shallow copy

For properties of primitive type, the shallow copy copies the property value to the new object, and for properties of reference type, the shallow copy copies the reference to the new object. While reference types like String and Integer are not immutable, copying creates a new memory space to hold the value and points the new reference to the new memory space. Immutable types are special reference types, and we will assume that the application of these final types is also a copy value.

Shallow copy function is implemented

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Cloneable{

    private int age;
    private String name;
    private Dept dept;
    @Override
    protected Object clone(a) throws CloneNotSupportedException {
        return super.clone(); }}Copy the code

How do we test our conclusions? First, compare the copied object with the original object to see if it is equal. If it is unequal, it indicates that it is a newly copied object. Then modify the basic type attribute of the copied object. If the attribute of the original object is changed, it indicates that the basic type attribute is the same. Finally, modify the reference type of the copied object, that is, Dept. Once we understand the principles of testing, we write a test code to verify our conclusions.

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

    Dept dept = new Dept(12."Marketing Department");
    User user = new User(18."Java journey", dept);

    User user1 = (User)user.clone();
    System.out.println(user == user1);
    System.out.println();

    user1.setAge(20);
    System.out.println(user);
    System.out.println(user1);
    System.out.println();

    dept.setName("R&d Department");
    System.out.println(user);
    System.out.println(user1);
}
Copy the code

The code above runs as follows

Name = deptNo, name= deptNo, name= deptNo, name= deptNo, name= deptNo, name= deptNo Name =' deptNo ', name=' deptNo ', name=' deptNo ', name=' deptNo ', name=' deptNo ' Name =' r&d department '}}Copy the code

Deep copy

In contrast to shallow copy, deep copy copies not only the properties of the base type, but also the properties of the reference type.

The deep copy function is implemented

When you copy user, copy the DEPT property of user.

Dept:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Cloneable {

    private int deptNo;
    private String name;

    @Override
    public Object clone(a) throws CloneNotSupportedException {
        return super.clone(); }}Copy the code

The user class:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Cloneable{

    private int age;
    private String name;
    private Dept dept;

    @Override
    protected Object clone(a) throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.dept =(Dept) dept.clone();
        returnuser; }}Copy the code

Continue the test with the shallow-copy test code and run the following:

false

User{age=18, name='Java journey', dept=Dept{deptNo=12, name='Marketing Department'}}
User{age=20, name='Java journey', dept=Dept{deptNo=12, name='Marketing Department'}}

User{age=18, name='Java journey', dept=Dept{deptNo=12, name='研发部'}}
User{age=20, name='Java journey', dept=Dept{deptNo=12, name='Marketing Department'}}
Copy the code

In addition, you can implement deep copy with deserialization, serializing an object to a stream of bytes, and then serializing a stream of bytes to an object, which produces a new object.

See you later: deep copy, shallow copy problem! – CodeSheep

Focus, don’t get lost

If you think the article is good, please pay attention to it, like it, and save it. Your support is the motivation for my creation. Thank you all.

If there is a problem with the article, please don’t be stingy with the writing, welcome to point out the message, I will check and revise in time.

If you want to see more things, you can search “Java Journey” on wechat to follow. “Java Journey” has compiled various middleware tutorials and various Java-related interview questions. This information can be obtained by scanning the QR code below to follow.