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
    评论
4S店客户管理小程序-毕业设计,基于微信小程序+SSM+MySql开发,源码+数据库+论文答辩+毕业论文+视频演示 社会的发展和科学技术的进步,互联网技术越来越受欢迎。手机也逐渐受到广大人民群众的喜爱,也逐渐进入了每个用户的使用。手机具有便利性,速度快,效率高,成本低等优点。 因此,构建符合自己要求的操作系统是非常有意义的。 本文从管理员、用户的功能要求出发,4S店客户管理系统中的功能模块主要是实现管理员服务端;首页、个人中心、用户管理、门店管理、车展管理、汽车品牌管理、新闻头条管理、预约试驾管理、我的收藏管理、系统管理,用户客户端:首页、车展、新闻头条、我的。门店客户端:首页、车展、新闻头条、我的经过认真细致的研究,精心准备和规划,最后测试成功,系统可以正常使用。分析功能调整与4S店客户管理系统实现的实际需求相结合,讨论了微信开发者技术与后台结合java语言和MySQL数据库开发4S店客户管理系统的使用。 关键字:4S店客户管理系统小程序 微信开发者 Java技术 MySQL数据库 软件的功能: 1、开发实现4S店客户管理系统的整个系统程序; 2、管理员服务端;首页、个人中心、用户管理、门店管理、车展管理、汽车品牌管理、新闻头条管理、预约试驾管理、我的收藏管理、系统管理等。 3、用户客户端:首页、车展、新闻头条、我的 4、门店客户端:首页、车展、新闻头条、我的等相应操作; 5、基础数据管理:实现系统基本信息的添加、修改及删除等操作,并且根据需求进行交流信息的查看及回复相应操作。
现代经济快节奏发展以及不断完善升级的信息化技术,让传统数据信息的管理升级为软件存储,归纳,集中处理数据信息的管理方式。本微信小程序医院挂号预约系统就是在这样的大环境下诞生,其可以帮助管理者在短时间内处理完毕庞大的数据信息,使用这种软件工具可以帮助管理人员提高事务处理效率,达到事半功倍的效果。此微信小程序医院挂号预约系统利用当下成熟完善的SSM框架,使用跨平台的可开发大型商业网站的Java语言,以及最受欢迎的RDBMS应用软件之一的MySQL数据库进行程序开发。微信小程序医院挂号预约系统有管理员,用户两个角色。管理员功能有个人中心,用户管理,医生信息管理,医院信息管理,科室信息管理,预约信息管理,预约取消管理,留言板,系统管理。微信小程序用户可以注册登录,查看医院信息,查看医生信息,查看公告资讯,在科室信息里面进行预约,也可以取消预约。微信小程序医院挂号预约系统的开发根据操作人员需要设计的界面简洁美观,在功能模块布局上跟同类型网站保持一致,程序在实现基本要求功能时,也为数据信息面临的安全问题提供了一些实用的解决方案。可以说该程序在帮助管理者高效率地处理工作事务的同时,也实现了数据信息的整体化,规范化与自动化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值