tags:

views:

54

answers:

2

Is the element in the Vector a clone/copy of the original?

SomeType myVar = new SomeType();
myVar.something = "AStringValue";
myVar.i = 123;

Vector<SomeType> v1 = new Vector<SomeType>();
v1.add(myVar);
Vector<SomeType> v2 = new Vector<SomeType>();
v2.add(myVar);

v1.get(0).i = 321;

After this code are these statements true v2.get(0).i == 321, myVar.i == 321?

+5  A: 

No, the Vector contains a reference to the original object - as does your myVar variable. It's very important to understand that a variable (or indeed any expression) can never actually have a value which is an object. The value is either a primitive type value (an integer, character etc) or a reference to an object, or null.

When you call v1.add(myVar), that copies the value of myVar into the vector... that value being the reference. When you change the object that the reference refers to, that change will be visible via all references to the object.

Think of it this way: suppose I have a house with a red door, and give my address to two different people. The first person comes and paints my door green. If the second person comes and looks at the house, he'll see that the door is green too... because he's looking at the same house, via a copy of the reference (the street address in this case).

(As an aside, is there any reason you're still using Vector instead of the more common ArrayList? You're obviously using a recent-ish JDK, given that you're using generics...)

Jon Skeet
So v2.get(0).i myVar.i will be 321 too?
János Harsányi
@János, yes it will. Btw `Vector` is obsolete - it is preferable to use `ArrayList` instead.
Péter Török
I'm very happy to hear this :)
János Harsányi
@János: Is there anything stopping you from running the code to find out? ;)
Jon Skeet
I just wanted to make sure.Btw I'm using `Vector` because I'm using a `JList` in an app. and `setListData` takes a `Vector` as parameter.
János Harsányi
+1  A: 

It's not a clone, it's a reference to the same object. If you update the one you get from the vector, you're updating the one you put into both vectors.

Paul Tomblin