Reputation: 69
So, when I try adding a Trick to an ArrayList the Trick that is added overwrites what is already in the ArrayList so that all the elements in the ArrayList consists of the trick I have just added.
These methods are in my main class:
public Trick playTrick(Player firstPlayer){
Trick t=new Trick(firstPlayer.getID());
return t;
}
public void playGame(){
for(int i=0;i<NOS_TRICKS;i++){
Trick t=playTrick(players[firstPlayer]);
players[firstPlayer].update(t);
//System.out.println(t.completedTricks);
}
}
The error is occurring when players[firstPlayer].update(t) is called, update(t) adds Trick t to my ArrayList:
public class BPlayer implents Player{
public void update(Trick t){
this.strategy.updateData(t);
}
}
This then triggers updateData:
public class AdvStrategy implements Strategy{
public static ArrayList<Trick> completedTricks = new ArrayList<>();
@Override
public void updateData(Trick c) {
completedTricks.add(c);
}
}
Example of my output when printing the ArrayList:
Trick ={3=KING DIAMONDS, 0=TWO DIAMONDS, 1=THREE DIAMONDS, 2=FIVE DIAMONDS}
Lead =3 Winner =3 DIAMONDS
ARRAYLIST[{3=KING DIAMONDS, 0=TWO DIAMONDS, 1=THREE DIAMONDS, 2=FIVE DIAMONDS}]
Trick ={3=QUEEN DIAMONDS, 0=FOUR DIAMONDS, 1=SIX DIAMONDS, 2=TEN DIAMONDS}
Lead =3 Winner =3 DIAMONDS
ARRAYLIST[{3=QUEEN DIAMONDS, 0=FOUR DIAMONDS, 1=SIX DIAMONDS, 2=TEN DIAMONDS}, {3=QUEEN DIAMONDS, 0=FOUR DIAMONDS, 1=SIX DIAMONDS, 2=TEN DIAMONDS}]
Last line of output should be this when working...
ARRAYLIST[{3=KING DIAMONDS, 0=TWO DIAMONDS, 1=THREE DIAMONDS, 2=FIVE DIAMONDS}, {3=QUEEN DIAMONDS, 0=FOUR DIAMONDS, 1=SIX DIAMONDS, 2=TEN DIAMONDS}]
Upvotes: 0
Views: 1805
Reputation: 533492
When you write Trick t
this is a reference to a Trick and when you add this reference to an ArrayList, the reference is copied not the object it references. This means if you add the same reference to a List more than once and you alter the object it references, it appears that all object have changed before there is actually only one.
Somewhere in your code, you are adding the same reference more than once. I suggest you step through your code in your debugger to see exactly where this happens.
Alternatively you could check whether the Trick you are about to add is already in the list and throw an error if it is.
Upvotes: 2