Clone Versus Copy Constructor

Prefer a copy constructor over clone(): a shallow clone shares mutable list state, while an explicit constructor copies fields deliberately.

JavaData Integrity

Code

snippet
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);
    }
}

How execution unfolds

The code’s whole job belongs to the class Inventory and the functions Inventory, clone, add and toString.

The AssertionError is not a guard against bad input: it wraps the CloneNotSupportedException declared by super.clone(), which cannot fire once Inventory implements Cloneable — the catch (CloneNotSupportedException cannotHappen) branch is unreachable protocol scaffolding, kept only because the compiler demands the checked exception be handled.

Watch out for

  • All symbols resolve to language built-ins — nothing gets fetched.

Using it

Signature: public Inventory(List<String> items)

The run emits 3 labeled sections — original:, clone:, copied: — one per step.

Launch the file; main takes over and steps through Inventory, clone and add.

Key statements

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

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
`AssertionError` is raised at the guard, so invalid state never reaches the main logic.
What does Clone Versus Copy Constructor print when run?
Run it as a complete program — the output lines carry labels such as `original:`, `clone:`, `copied:`.