CFleming
CFleming

Reputation: 19

Java List of Points

So I'm having a problem with this line of code.

private List<PointF> userPath = new ArrayList<PointF>();
pointF movingPoint = new pointF();
pointF initialPoint = new pointF();
initialPoint = (1,1);

for (i = 0; i < 5; i++)
{
    movingPoint.x = initialPoint.x + i;
    movingPoint.y = initialPoint.y;

    userPath.add(movingPoint);
}

So what I want is for the userPath List to have each coordinate, [(1,1), (2,1), (3,1)...]

Instead I keep getting [(1,1)] first iteration [(2,1), (2,1)] second iteration [(3,1), (3,1), (3,1)] third iteration

Is there a way I can work around this, since I realize that each element of the List is storing the point object movingPoint and when moving point changes so does every element which contains it.

Upvotes: 0

Views: 1682

Answers (1)

AntonH
AntonH

Reputation: 6437

You have to re-create movingPoint at each iteration of the loop.

private List<PointF> userPath = new ArrayList<PointF>();
pointF movingPoint = null; // change here
pointF initialPoint = new pointF();
initialPoint = (1,1);

for (i = 0; i < 5; i++)
{
    movingPoint = new pointF(); // change here

    movingPoint.x = initialPoint.x + i;
    movingPoint.y = initialPoint.y;

    userPath.add(movingPoint);
}

If you don't re-create it, since you,re keeping the reference, you're basically adding the same object several times to the list. So any modification to the object movingPoint with affect all the objects of the list, since they all have the same reference to the same object.

Upvotes: 2

Related Questions