سؤال

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