开发者

Java Vector Question

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

SomeType myVar = new SomeType();
myVar.something = "AStringValue";
myVar开发者_StackOverflow中文版.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?


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...)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜