In below class I am adding a String to a Vector(v1) and then adding that Vector(v1) to a new Vector(v2). I then re-initialise Vector v1.
How does java retain the reference to v1 ? When I re-initalise v1 is java maintaining a reference under the hood ?
The output of below is “1”.
public class VectorTest {
public static void main(String args[]){
new VectorTest().testVector();
}
private void testVector(){
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("1");
v2.add(v1);
v1 = new Vector();
Vector v3 = (Vector)v2.get(0);
System.out.println(v3.elementAt(0));
}
}
You’re changing what
v1refers to, in this case some otherVector. Butv2still holds a reference to the originalVector.Objects in Java can have multiple variables referring to it.
Vectorobjects are also mutable, meaning that if one of its referrers modifies it, like you do with:Then every other referrer will now reference that same vector that has a
"1"in it.You can also change what objects a variable refers to, like you do here:
So after that happens,
v1holds a different reference to a differentVectorobject, whilev2[0](excuse the array notation) still holds a reference to the originalVectoryou created and assigned tov1at the beginning.When you do this, you’re making
v3refer to the sameVectorthat you created at the beginning, so there are two referrers to this object at this point:v2[0]v3I’d try to draw some crude images to demonstrate this, but I think it’s easier just to read this page from the Java tutorial about objects and references:
http://download.oracle.com/javase/tutorial/java/javaOO/objectcreation.html