Java:向量添加函数是浅拷贝吗?

3

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

3个回答

3

这个向量只存储指向您添加的对象的指针,它不会创建“深层”副本。 (在Java中没有通用机制来创建任意对象的“深层”副本,因此库集合难以提供这样的功能!)


1

这是浅拷贝,实际上根本不是拷贝,列表具有对同一对象的引用。如果您想进行深拷贝,请使用实现Cloneable接口和方法clone()或使用复制构造函数。


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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接