← 中文资源

简体中文版本

克隆与拷贝构造器

用拷贝构造器替代 clone():Cloneable 标记加浅拷贝会让两个对象共享同一个 List,显式构造器按语义复制字段,也不受克隆协议的异常约束。

阅读英文原文

实现说明

活动部件是类 Inventory和函数 Inventory、clone、add、toString。 AssertionError 之前有一道守卫:坏状态在这里就停下,不会继续往下走。

使用要点

  • 每一步打印都带着自己的标签:original:、clone:、copied:。
  • 运行整个文件:main 会依次驱动 Inventory、clone、add。

常见问题

遇到格式错误的数据会怎样?

守卫处(入口)会抛出 AssertionError,非法状态到不了主逻辑。

运行「克隆与拷贝构造器」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 original:、clone:、copied: 这类标签。

主签名形如 public Inventory(List<String> items)

核心语句

throw new AssertionError(cannotHappen);
return items.toString();

代码示例

import java.util.ArrayList;
import java.util.List;

public class Inventory implements Cloneable {

    private List<String> items; // 非 final:clone 后需重新赋值才能深拷贝

    public Inventory(List<String> items) {
        // 构造器入口先做防御性拷贝,外界传入的列表变化不影响内部状态
        this.items = new ArrayList<>(items);
    }

    // 拷贝构造器 (copy constructor):final 字段也能复制,语义显式可读
    public Inventory(Inventory other) {
        this(new ArrayList<>(other.items));
    }

    // clone() 需要 Cloneable 标记接口;super.clone() 浅拷贝,List 引用被共享
    @Override
    public Inventory clone() {
        try {
            Inventory copy = (Inventory) super.clone();
            copy.items = new ArrayList<>(this.items); // 手动复制才彻底隔离
            return copy;
        } catch (CloneNotSupportedException cannotHappen) {
            throw new AssertionError(cannotHappen);
        }
    }

    public void add(String item) {
        items.add(item);
    }

    @Override
    public String toString() {
        return items.toString();
    }

    public static void main(String[] args) {
        Inventory original = new Inventory(List.of("bolt", "nut"));
        Inventory cloned = original.clone();
        Inventory copied = new Inventory(original);

        original.add("washer");
        System.out.println("original: " + original);
        System.out.println("clone:    " + cloned);
        System.out.println("copied:   " + copied);
    }
}