【JAVA基础面经】深拷贝与浅拷贝

文章目录


基本概念

  • 浅拷贝:创建一个新对象,然后将原对象的非静态字段(基本类型和引用类型)直接复制到新对象中。对于引用类型字段,复制的是引用地址,即新对象和原对象中的引用字段指向同一个实例。因此,修改其中一个对象的引用字段内容,会影响另一个对象。

  • 深拷贝:创建一个新对象,并递归地复制原对象中所有引用类型字段所引用的对象,直到所有层次都被完全复制。新对象和原对象完全独立,修改一个不会影响另一个。


浅拷贝

&emap;默认的 super.clone() 执行的是浅拷贝,此时p1 和 p2 的 address 引用指向同一个 Address 对象,因此修改 p2 的地址会影响 p1

java 复制代码
class Address {
    String city;
    Address(String city) { this.city = city; }
    // getter/setter 省略
}

class Person implements Cloneable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 浅拷贝
    }

    // getter/setter 省略
}

public class ShallowCopyDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address addr = new Address("北京");
        Person p1 = new Person("张三", addr);
        Person p2 = (Person) p1.clone();

        System.out.println(p1.address.city); // 北京
        System.out.println(p2.address.city); // 北京

        // 修改 p2 的地址
        p2.address.city = "上海";
        System.out.println(p1.address.city); // 上海 → 影响原对象
        System.out.println(p2.address.city); // 上海
    }
}

深拷贝

重写 clone() 方法实现深拷贝

 在 clone() 方法中,不仅要调用 super.clone(),还要对引用类型字段手动进行拷贝(通常也调用其 clone() 方法,要求被引用的类也支持克隆)。

java 复制代码
class Address implements Cloneable {
    String city;
    Address(String city) { this.city = city; }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // Address 内部只有基本类型/不可变,浅拷贝即可
    }
}

class Person implements Cloneable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person cloned = (Person) super.clone();   // 浅拷贝基础字段
        cloned.address = (Address) address.clone(); // 深拷贝 address
        return cloned;
    }
}

使用序列化实现深拷贝

 将对象写入流再从流中读出,可以自动实现深拷贝(要求所有引用类型都实现 Serializable 接口)。序列化方式的优点是不需要为每个类手动编写拷贝逻辑,但要求所有涉及类都实现 Serializable,且性能相对较低。

java 复制代码
import java.io.*;

class Address implements Serializable {
    String city;
    Address(String city) { this.city = city; }
}

class Person implements Serializable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    // 深拷贝方法
    public Person deepCopy() {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(this);
            try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bis)) {
                return (Person) ois.readObject();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}

使用复制构造函数或工厂方法

 手动编写一个构造函数,接收同类型对象并逐一复制字段,对于引用类型也递归复制。这种方式清晰直观,但需要为每个类编写拷贝逻辑,且当对象图复杂时容易遗漏。

java 复制代码
class Address {
    String city;
    Address(String city) { this.city = city; }
    // 复制构造函数
    Address(Address other) {
        this.city = other.city;
    }
}

class Person {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }
    // 复制构造函数(深拷贝)
    Person(Person other) {
        this.name = other.name;
        this.address = new Address(other.address); // 复制 address
    }
}
相关推荐
何以解忧,唯有..11 分钟前
Redis 过期事件监听:原理与实战
java
weixin_3077791319 分钟前
C++代码实现MATLAB中的ode45函数功能
开发语言·c++·算法·matlab
风中的小熊生气22 分钟前
Spring Boot 面试知识(二):分层、IoC、异常、配置与 Redis
java·springboot
泡茶喝茶写代码23 分钟前
量化数据开发实战系列(第 25 篇):基金基础接口实战:基金列表、ETF-LOF 分类、基金概况、净值数据
java·数据库·人工智能·python·mysql
不穿鞋的懒羊羊43 分钟前
dfs深度优先搜索
算法
是立不是利1 小时前
大文件导致请求被拒的连锁反应
开发语言·前端·javascript
OYYHXPJR1 小时前
【算法】区间重叠模板和矩形重叠模板
算法
shehuiyuelaiyuehao1 小时前
算法46,分治快排,排序数组
java·算法·排序算法·排序
野生技术架构师1 小时前
1200 道 JAVA 面试题(各大企业常见面试题及答案)
java·开发语言
careathers1 小时前
【数据结构】栈
java·数据结构