当您使用add函数将对象添加到向量中时,它是浅复制还是深复制? 如果它是浅层复制,这意味着如果您更改向量中的对象,则会更改对象的原始副本。
当您使用add函数将对象添加到向量中时,它是浅复制还是深复制? 如果它是浅层复制,这意味着如果您更改向量中的对象,则会更改对象的原始副本。
这个向量只存储指向您添加的对象的指针,它不会创建“深层”副本。 (在Java中没有通用机制来创建任意对象的“深层”副本,因此库集合难以提供这样的功能!)
例如,它很浅。
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());