3

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

4

3 回答 3

3

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

于 2012-11-30T20:18:26.503 回答
1

它是浅拷贝,实际上它根本不是拷贝,列表具有对同一对象的引用。如果要传递深层副本,请使用实现Cloneable iface 和方法 clone() 或者您可以使用复制构造函数。

于 2012-11-30T20:19:03.343 回答
0

例如,它很浅。

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());
于 2012-11-30T20:23:05.240 回答