Deep, Shallow and Lazy Copy in Java

一、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》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值