ArrayList does not save my Values

following: I create a ArrayList with an Own Object which keeps two int(x,y)

But I only get 0 instead of the number. I don't see why it does not work.

public class Snake {

public class SnakeBody {
    public int x;
    public int y;
    SnakeBody(int x, int y){
        x = this.x;
        y = this.y;}
}

protected ArrayList<SnakeBody> SnakeBody = new ArrayList<SnakeBody>();
protected PointF Fruit;

protected boolean GameStarted = false;

//Constructor
public Snake(){}

public void startSnake()
{
    if(!GameStarted)
    {
        GameStarted = true;
        SnakeBody.add(new SnakeBody(1,14));
        SnakeBody.add(new SnakeBody(2,14));
        SnakeBody.add(new SnakeBody(3,14));
        int itemcount = SnakeBody.size();
        Log.d("Snake.java:Game started: ", "" + itemcount);
        for(int i=0; i<itemcount; i++){
            Log.d("First Snake created: XY->", "" + SnakeBody.get(i).x + ":" + SnakeBody.get(i).y);
        }
    }
}

That's what I got then as Log.d Output:

Snake.java:Game started:﹕ 3

First Snake created: XY->﹕ 0:0

First Snake created: XY->﹕ 0:0

First Snake created: XY->﹕ 0:0

Jon Skeet
people
quotationmark

Look at your constructor:

SnakeBody(int x, int y){
        x = this.x;
        y = this.y;}

That's copying the value from your instance field to the parameter, in both cases. In other words, you're overwriting the useful data (the value that the caller passed in) with the value from the otherwise-uninitialized field (which will always be 0). You want it the other way round:

SnakeBody(int x, int y) {
    this.x = x;
    this.y = y;
}

Note that this has nothing to do with the ArrayList aspect - you could observe the same thing just by writing:

SnakeBody body = new SnakeBody(1, 2);
System.out.println(body.x); // 0

It's always worth trying to pinpoint exactly where the issue is, trying to remove bits of code one at a time until the behaviour changes.

(It's also a good idea to make all fields private, but that's a slightly different matter.)

people

See more on this question at Stackoverflow