Deep, Shallow and Lazy Copy in Java

本文深入探讨了Java中对象的深拷贝与浅拷贝概念,解析了它们的区别及应用场景,包括引用拷贝、对象拷贝、懒拷贝等,并介绍了实现拷贝的多种方式,如clone()方法、复制构造器、工厂方法、序列化/反序列化等。
一、What Is a Copy?

Reference Copy
As the name implies, creates a copy of a reference variable pointing to an object.

在这里插入图片描述
Object Copy
An object copy creates a copy of the object itself.
在这里插入图片描述)

二、What Is an Object?

Often, when we talk about an object, we speak of it as a single unit that can’t be broken down further, like a humble coffee bean. However, that’s oversimplified.
Say we have a Person object. Our Person object is in fact composed of other objects, as you can see in Example 4. Our Person contains a Name object and an Address object. The Name in turn, contains a FirstName and a LastName object; the Address object is composed of a Street object and a City object. So when I talk about Person in this article, I’m actually talking about this entire network of objects.
在这里插入图片描述)

三、Shallow Copy

First let’s talk about the shallow copy. A shallow copy of an object copies the ‘main’ object, but doesn’t copy the inner objects. The ‘inner objects’ are shared between the original object and its copy. For example, in our Person object, we would create a second Person, but both objects would share the same Name and Address objects.

Let’s look at a coding example. In Example 5, we have our class Person, which contains a Name and Address object. The copy constructor takes the originalPerson object and copies its reference variables.

public class Person {
    private Name name;
    private Address address;
    public Person(Person originalPerson) {
         this.name = originalPerson.name;
         this.address = originalPerson.address;
    }
[…]
}

The problem with the shallow copy is that the two objects are not independent. If you modify the Name object of one Person, the change will be reflected in the other Person object.

Let’s apply this to an example. Say we have a Person object with a reference variable mother; then, we make a copy of mother, creating a second Person object, son. If later on in the code, the son tries to moveOut() by modifying his Address object, the mother moves with him!

Person mother = new Person(new Name(…), new Address(…));
[…]
Person son  = new Person(mother);
[…]
son.moveOut(new Street(…), new City(…));

This occurs because our mother and son objects share the same Address object, as you can see illustrated in Example 7. When we change the Address in one object, it changes in both!
在这里插入图片描述
summary:

  • Whenever we use default implementation of clone method we get shallow copy of object means it creates new instance and copies all the field of object to that new instance and returns it as object type, we need to explicitly cast it back to our original object. This is shallow copy of the object.
  • clone() method of the object class support shallow copy of the object. If the object contains primitive as well as nonprimitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves.
  • That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.
四、Deep Copy

Unlike the shallow copy, a deep copy is a fully independent copy of an object. If we copied our Person object, we would copy the entire object structure.
A change in the Address object of one Person wouldn’t be reflected in the other object as you can see by the diagram in Example 8. If we take a look at the code in example 9, you can see that we’re not only using a copy constructor on our Person object, but we are also utilizing copy constructors on the inner objects as well.

public class Person {
    private Name name;
    private Address address;
    public Person(Person otherPerson) {
         this.name    =  new Name(otherPerson.name);
         this.address =  new Address(otherPerson.address);
    }
[…]
}

Using this deep copy. Now the son is able to successfully move out!

However, that’s not the end of the story. To create a true deep copy, we need to keep copying all of the Person object’s nested elements, until there are only primitive types and “Immutables” left. Let’s look at the Street class to better illustrate this:


public class Street {
    private String name;
    private int number;
    public Street(Street otherStreet){
         this.name = otherStreet.name;
         this.number = otherStreet.number;
    }
[…]
}

The Street object is composed of two instance variables – String name and int number. int number is a primitive value and not an object. It’s just a simple value that can’t be shared, so by creating a second instance variable, we are automatically creating an independent copy. String is an Immutable. In short, an Immutable is an Object, that, once created, can never be changed again. Therefore, you can share it without having to create a deep copy of it.

Summary:

  • Whenever we need own copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need.
  • So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class.
五、Lazy Copy

A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach – at the initial state, shallow copy approach is used. A counter is also used to keep a track on how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.

六、Different ways to copy an object
1. clone()

The clone() method is defined in class Object which is the superclass of all classes. The method can be used on any object, but generally, it is not advisable to use this method.

class Car implements Cloneable {

    private String make;
    private int doors;
    private Motor motor;
    private Gearbox gearbox;

    …
    @Override
    public Car clone() {
        try {
           //Use Object.clone to create a copy of the correct type and do a field-by-field copy
            Car c = (Car) super.clone();

            // Already copied by Object.clone
            // c.doors = doors;
            
            // Clone children to produce a deep copy
            c.motor = motor.clone();
            c.gearbox = gearbox.clone();

            // No need to clone immutable objects
            // c.make = make; 
            
            return c;
        } catch (CloneNotSupportedException e) {
            // Will not happen in this case
            return null;
        }
    }
    …
}

Usage:

Car copy = (Car) originalCar.clone();

Unfortunately the cloning API is poorly designed and should almost always be avoided. Copying arrays is a notable exception where cloning is the preferred method.
Pros:
Automatic shallow copying
Deals with inheritance
Works well for arrays
Cons:
Casts required
No constructors called
Incompatible with final fields
CloneNotSupported is checked
Can’t opt out from being Cloneable

The black magic of Object.clone
Object.clone achieves two things that ordinary Java methods can’t:

  • It creates an instance of the same type as this, i.e. the following always holds:
super.clone().getClass() == this.getClass()
  • It then copies all fields from the original object to the clone.

It manages to do this without invoking any constructors and the field-by-field copy includes private and final fields.
But… how!? The Object.clone method is native:

protected native Object clone() throws CloneNotSupportedException;

This means that it’s implemented as part of a system library, typically written in C or C++. This allows it to use low level calls such as memcpy, ignore access modifiers, and do other things ordinary Java methods can’t.

2. Copy Constructors
public class Car {

    private String make;
    private int doors;
    private Motor motor;
    private Gearbox gearbox;

    public Car(Car other) {
        this.make = other.make;
        this.doors = other.doors;
        this.motor = other.motor;
        this.gearbox = other.gearbox;
    }
    …
}

Usage:

Car copy = new Car(original);

Note that this produces a shallow copy. If you do original.getGearbox().setGear(4), then copy’s gear will change as well. To get a deep copy, change to…

…
    public Car(Car other) {
        this.make = other.make;
        this.doors = other.doors;
        this.motor = new Motor(other.motor);
        this.gearbox = new Gearbox(other.gearbox);
    }
…

Copy Constructors and Inheritance
Adding a subclass, Taxi is straight forward:

public class Taxi extends Car {

    boolean isAvailable;

    public Taxi(Taxi other) {
        // Invoke copy constructor of Car
        super(other);

        this.isAvailable = other.isAvailable;
    }
    …
}

However, when using a copy constructor you must know the actual runtime type. If you’re not careful, you may inadvertently create a Car when trying to create a copy of a Taxi.

Car copy = new Car(someCar); // What if someCar is a Taxi?!

You could use instanceof (often considered bad practice) or the visitor pattern to sort it out, but in this case you’re probably better off using one of the other techniques described in this article.

Pros:
Simple and straight forward
Easy to get right, debug and maintain
No casts required
Cons:
You need to know the runtime type
Requires some boilerplate

3.Copy Factory Methods

A copy factory method encapsulates the object copying logic and provides finer control over the process. In the example below, this capability is used to tacle the problem of inheritance mentioned in the previous section.

public class CarFactory {
    …
    public Car copyOf(Car c) {
        Class<?> cls = c.getClass();
        if (cls == Car.class) {
            return new Car(
                    c.make,
                    c.doors,
                    c.motor,
                    c.gearbox);
        }
        if (cls == Taxi.class) {
            return new Taxi(
                    c.make,
                    c.doors,
                    c.motor,
                    c.gearbox,
                    ((Taxi) c).isAvailable);
        }
        if (cls == Ambulance.class) {
            return new Ambulance(
                    c.make,
                    c.doors,
                    c.motor,
                    c.gearbox,
                    ((Ambulance) c).beaconsOn);
        }
        throw new IllegalArgumentException("Can't copy car of type " + cls);
    }
    …
}

Usage:

Car copy = myCarFactory.copyOf(car);

Pros:
Finer control over object creation
All copying logic in one place
Cons:
Another level of indirection
Not as easy to extend
Might require access to internal state

4.Builders

When using the builder pattern it’s common to provide a way to initialize the state of the builder with the state of a given object. Creating a copy of a car c could look like new Car.Builder©.build().

5.Serialization / deserialization

By serializing an object, then deserializing the result you end up with a copy. If you already have a library such as Jackson set up for json serialization, you can reuse this for cloning.

Another alternative is to use the Serializable mechanism and ObjectInputStream/ObjectOutputStream but then you trade one type of black magic for another.

参考:
《Shallow vs. Deep Copy in Java》
《The Object clone() Method》
《Java: Copying Objects》
《Java: Clone and Cloneable》
《Deep, Shallow and Lazy Copy with Java Examples》

根据原作 https://pan.quark.cn/s/459657bcfd45 的源码改编 Classic-ML-Methods-Algo 引言 建立这个项目,是为了梳理和总结传统机器学习(Machine Learning)方法(methods)或者算法(algo),和各位同仁相互学习交流. 现在的深度学习本质上来自于传统的神经网络模型,很大程度上是传统机器学习的延续,同时也在不少时候需要结合传统方法来实现. 任何机器学习方法基本的流程结构都是通用的;使用的评价方法也基本通用;使用的一些数学知识也是通用的. 本文在梳理传统机器学习方法算法的同时也会顺便补充这些流程,数学上的知识以供参考. 机器学习 机器学习是人工智能(Artificial Intelligence)的一个分支,也是实现人工智能最重要的手段.区别于传统的基于规则(rule-based)的算法,机器学习可以从数据中获取知识,从而实现规定的任务[Ian Goodfellow and Yoshua Bengio and Aaron Courville的Deep Learning].这些知识可以分为四种: 总结(summarization) 预测(prediction) 估计(estimation) 假想验证(hypothesis testing) 机器学习主要关心的是预测[Varian在Big Data : New Tricks for Econometrics],预测的可以是连续性的输出变量,分类,聚类或者物品之间的有趣关联. 机器学习分类 根据数据配置(setting,是否有标签,可以是连续的也可以是离散的)和任务目标,我们可以将机器学习方法分为四种: 无监督(unsupervised) 训练数据没有给定...
在SystemVerilog中,浅拷贝和深拷贝主要用于处理复合对象(如包含其他对象的对象),二者存在明显差异且具有不同的用途。 浅拷贝只复制指向对象的指针,而不复制引用对象本身。也就是说,原对象和拷贝对象指向同一个内存资源,复制的仅仅是一个指针,对象本身资源只有一份。若对拷贝对象执行修改操作,原对象引用的对象同样会被修改,这可能违背复制拷贝的初衷。例如: ```systemverilog class MyClass; int data; function new(int val); data = val; endfunction endclass module test; MyClass obj1, obj2; initial begin obj1 = new(10); obj2 = obj1; // 浅拷贝 obj2.data = 20; $display("obj1.data: %0d", obj1.data); // 输出20,因为obj1和obj2指向同一对象 end endmodule ``` 深拷贝则是复制引用对象本身,在内存中存在两份独立的对象。对拷贝对象进行修改操作不会影响原对象。例如: ```systemverilog class MyClass; int data; function new(int val); data = val; endfunction function MyClass clone(); clone = new(data); endfunction endclass module test; MyClass obj1, obj2; initial begin obj1 = new(10); obj2 = obj1.clone(); // 深拷贝 obj2.data = 20; $display("obj1.data: %0d", obj1.data); // 输出10,因为obj1和obj2是独立的对象 end endmodule ``` 浅拷贝的目的在于快速复制对象,只复制指针,开销较小,适用于不需要独立副本的场景。深拷贝的目的是创建对象的完全独立副本,避免修改拷贝对象时影响原对象,适用于需要独立操作副本的场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值