I am quite new to programming in Java, but I have some experience in c/c++, I am noticing some unwanted behaviour in some of my code, and I am just wondering how to fix it.
This is what I have:
List<State> list = new ArrayList<State>();
State cur = new State();
cur.x = 1;
cur.y = 1;
list.add(cur);
cur.x = 2;
cur.y = 3;
list.add(cur);
cur.x = 3;
cur.y = 4;
list.add(cur);
for (State i : list)
System.out.println(i.x + " " + i.y);
class State
{
public int x = 0;
public int y = 0;
}
This gives me an output of:
3 4
3 4
3 4
Where as I want the output to be:
1 1
2 3
3 4
How do I fix this?
Thanks,
paintstripper
The problem you have is that you’re mutating a single object. It’s better to avoid publicly mutable member variables. If you write the State class as below you would not have been able to make the programming error.
Note the final keyword on the x and y members, this means they cannot be assigned to after construction.