When you use the add function to add an object to a vector, is it a shallow copy or deep copy? If it's shallow it means if you change the objects in the vector you would change the original copy of the object?

有帮助吗?

解决方案 2

it is shallow copy, well actually it is not copy at all, the list has the reference to the same object. If you want to pass the deep copy, use implement Cloneable iface and method clone() or you can use a copy constructor.

其他提示

The vector only holds a pointer to the object you added, it does not create 'deep' copies. (There is no universal mechanism in Java by which a 'deep' copy of any arbitrary Object is created, so it would be tough for a library collection to offer such functionality!)

It is shallow, for instance.

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());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top