Java Question: References

Status
Not open for further replies.

abcfob11

Ars Tribunus Militum
2,025
Subscriptor
Ok, here we go

say i have the following (massively simplified)

Token dummy = new Token(); //Token is just some object

//feeble and weeble are both instances of some class with a vector in it

feeble.add(dummy) //the add functions add it to a Vector
weeble.add(dummy)

so, if i change dummy, will the entries in both vectors be changed?

It should right? Just making sure.
 

fats

Ars Praefectus
4,599
Subscriptor
No. Here, consider this simple example that I have tested.

Rectangle red = new Rectangle(50, 50, 50, 50, Color.red, true);
Vector v = new Vector();
v.add(red);
red = new Rectangle(100, 100, 50, 50, Color.blue, false);
Rectangle whichIsIt = (Rectangle)Vector.elementAt(0);

Examination of whichIsIt in a debugger will show you that whichIsIt is a Rectangle with these values: 50, 50, 50, 50, Color.red, true

Vectors do not store references to objects. They copy objects that are loaded into them and store the copies.
 

w.anders

Ars Tribunus Angusticlavius
6,957
Actually, much like HeadlessCow said, vectors <big>do</big> store references to objects, as shown below:

Code:
<code><big><font color="#00ff00">import</font> java.util.*;<P><font color="#ffff00">public</font> <font color="#ffff00">class</font> VectorTester
{
  <font color="#ffff00">public</font> <font color="#ffff00">static</font> <font color="#ffff00">void</font> main(String[] args)
  {
    StringBuffer sbOne = <font color="#ffff00">new</font> StringBuffer(<font color="#00ffff">"First string"</font>);
    Vector v = <font color="#ffff00">new</font> Vector();<P>    v.add(sbOne);
    System.out.println((StringBuffer)v.firstElement()); <font color="#ffa500">// << First string >></font><P>    sbOne.delete(<font color="#00ffff">0</font>, <font color="#00ffff">6</font>);
    System.out.println((StringBuffer)v.firstElement()); <font color="#ffa500">// << string >></font>
  }
}</big></code>

What happens in fats example is that the <code><big>red</big></code> reference is pointed to a new object, so now <code><big>red</big></code> and <code><big>v.firstElement()</big></code> points to two different objects, rather than the same one.
 
Status
Not open for further replies.