Vector help

Hi,

I'm working on an international relations simulation project and having trouble getting information into vectors.

I've pasted a function below. The function goes through a Vector one element at a time, grabs the object at the index and returns that info (this is working).

Then there is an if statement, which is irrelevent for right now.

Then I try to add the element I just got into a different vector. I check by display the last element in the Vector and I appears to be going into the Vector correctly.

However, when I am finished adding to the second Vector, I display the contents of it and I get the first element (which is added in a different part of the code) and then the last element I added over and over again (The Vector size seems to be correct).

This may be a case of things somehow being overwritting?

I can't figure it out.

I pasted the function below.

Thanks for any help,

Andy

public static War callAllies(State[][] world, War activeWar,

Coordinates state, boolean init) {

Ally tempAl;

Coordinates tempCo = new Coordinates( -1, -1);

for (int counter = 0; counter < world[state.i][state.j].allies.size(); counter++) {

// this is working

tempAl = (Ally) world[state.i][state.j].allies.elementAt(counter);

tempCo.i = tempAl.allyI;

tempCo.j = tempAl.allyJ;

world[tempCo.i][tempCo.j].atWar++;

// check whether to add to the initiators vector or the targets

if (init) {

System.out.println("Adding to A");

activeWar.belligerentsA.addElement(tempCo);

} else {

System.out.println("Adding to B " + tempCo.i + "," + tempCo.j);

// I tried add and addElement and got the same results

//activeWar.belligerentsB.addElement(tempCo);

activeWar.belligerentsB.add(tempCo);

// this displays the correct info

System.out.println("Added " + ((Coordinates) activeWar.belligerentsB.lastElement()).i + "," +

((Coordinates) activeWar.belligerentsB.lastElement()).j);

}

}

// this loop is for debugging, checks to see whats in the Vector - right now it outputs the first element, and then the last element over and over again

for (int k = 0; k < activeWar.belligerentsB.size(); k++) {

tempCo = (Coordinates) activeWar.belligerentsB.elementAt(k);

System.out.println("In B: " +((Coordinates) activeWar.belligerentsB.elementAt(k)).i + "," +

((Coordinates) activeWar.belligerentsB.elementAt(k)).j);

}

return activeWar;

} // end call Allies

[2617 byte] By [bauschawa] at [2007-11-26 17:40:19]
# 1
Remember, a Vector stores references to an object. When adding and removing things from a Vector, you need to create copies or new() objects every time. Otherwise, you're overwriting and adding the same reference multiple times.
kevjavaa at 2007-7-9 0:08:29 > top of Java-index,Java Essentials,New To Java...