Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange scoping issues

Status
Not open for further replies.

qkslvrwolf

Programmer
Jul 9, 2002
28
US
I'm having a weird scoping issue where I add a new instantiation of a class (edge) to a Vector (edges). However, no matter how many layers of newness I add to the edge that I add, it creates a pointer to the same object...so I get a Vector with a bunch of copies of the last object that I add...

while (line != null)
{
StringTokenizer makeAToken = new StringTokenizer(line);
int w = Integer.valueOf(makeAToken.nextToken().trim()).intValue();
int n1 = Integer.valueOf(makeAToken.nextToken().trim()).intValue();
int n2 = Integer.valueOf(makeAToken.nextToken().trim()).intValue();
edge newEdge = new edge(w, n1, n2);
System.out.println(numEdges);
System.out.println(newEdge.weight);
addEdge(newEdge);
System.out.println( ((edge)edges.elementAt(0)).weight);
numEdges++;
line = r.readLine();
}

public static void addEdge(edge e1)
{
edge toAdd = new edge(e1);
edges.addElement(toAdd);
}

I was originally doing just edges.addElement(new edge(w, n1, n2)

(edge has 2 contructors, now)

but that was giving me the same issue.

Whats going on? Please help....
 
Could you show the code where you are looping through the edges (the part that help you determine you have multiple pointers to the same object) ? --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
For my next trick I will pull a hat out of a rabbit (if you think thats bad you should see how the pigeon feels...) :p
 
>> System.out.println( ((edge)edges.elementAt(0)).weight);

If you are counting on that line of code to view your Vector... you are only looking an the first element every time through the loop. The new objects are being append to the end of the Vector.

-pete
 
Sorry, should have mentioned that, I was already thinking one step past that in my post above, without mentioning palbano's point first :p
I assumed that since all of your pointers point to "the last object" you were at some point outputting the objects in a loop rather than just outputting the first object (which would point to the first object created). If this is not the case I apologize.

-Tarwn --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
For my next trick I will pull a hat out of a rabbit (if you think thats bad you should see how the pigeon feels...) :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top