shallow copy, deep copy, reference copy

Table of contents

1. Shallow copy

2. Deep copy

3. Reference copy

4. Code example

5. Summary


   Shallow copy, deep copy and reference copy are three different ways used in programming to  copy objects or data .

1. Shallow copy

Shallow Copy: A shallow copy creates a new object that contains a reference to the original object. This means that the new object and the original object will refer to the same memory address, and modifications to one will affect the other. In short, a shallow copy only copies the object's reference, not the object itself.

2. Deep copy

Deep Copy: A deep copy creates a new object and recursively copies the original object and all its nested objects. This means that the new object is completely independent from the original object, and modifications to one object will not affect the other. In short, a deep copy copies the entire object and its references.

3. Reference copy

Reference copy (Reference Copy): Reference copy simply points the new variable to the memory address of the original object without creating a new object. This means that both the old and new variables refer to the same object, and changes to one variable will also affect the other.

4. Code example

// 假设有一个Person类
class Person {
    public String name;
    
    public Person(String name) {
        this.name = name;
    }
}

// 创建一个原始对象
Person original = new Person("Alice");

// 浅拷贝示例
Person shallowCopy = original;
shallowCopy.name = "Bob";
System.out.println(original.name);  // 输出 "Bob",原始对象被修改

// 深拷贝示例
Person deepCopy = new Person(original.name);
deepCopy.name = "Charlie";
System.out.println(original.name);  // 输出 "Bob",原始对象未被修改

// 引用拷贝示例
Person referenceCopy = original;
referenceCopy.name = "Dave";
System.out.println(original.name);  // 输出 "Dave",原始对象被修改

5. Summary

For shallow copy and reference copy, modifying the copied object will affect the original object, but deep copy will not. Therefore, deep copy is the most thorough copy method, which can create independent copies of objects, while shallow copy and reference copy only create new references to the same object.

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/131599189