【问题标题】:Java: Vector add function is it shallow?Java:向量添加函数是不是很浅?
【发布时间】:2026-01-27 16:20:06
【问题描述】:

当你使用add函数将对象添加到vector时,是浅拷贝还是深拷贝? 如果它很浅,这意味着如果您更改向量中的对象,您将更改对象的原始副本?

【问题讨论】:

    标签: java vector deep-copy shallow-copy


    【解决方案1】:

    向量仅包含指向您添加的对象的指针,它不会创建“深度”副本。 (Java 中没有通用机制可以创建任意对象的“深度”副本,因此库集合很难提供这样的功能!)

    【讨论】:

      【解决方案2】:

      它是浅拷贝,实际上它根本不是拷贝,列表具有对同一个对象的引用。如果你想传递深拷贝,使用实现Cloneableiface 和方法clone() 或者你可以使用拷贝构造函数。

      【讨论】:

        【解决方案3】:

        例如,它很浅。

        Vector<MyObj> victor = new Vector<MyObj>();
        MyObj foo = new MyObj();
        MyObj bar = new MyObj();
        foo.setValue(5);
        bar.setValue(6);
        victor.add(foo);
        victor.add(bar);
        
        foo.setValue(3);
        victor.get(1).setValue(7);
        
        // output: 3, even though it went into the vector as 5
        System.out.println(victor.get(0).getValue()); 
        
        // output: 7, even though we changed the value of the vector 'object'
        System.out.println(bar.getValue());
        

        【讨论】: