0

I cannot find whats wrong with this code. I have short type array called "data". I assign data[i] value to private Point objects variable x then I add this object to ArrayList and proceed with next i. In the arraylist all instances have same value - last one that was added. Why do you think its so?

    ArrayList<Point> p = new ArrayList<Point>();

        System.out.println("start test");
    for (int i=0;i<data.length;i++){

        bPunkt.x=(int) data[i];
        p.add(bPunkt);
        System.out.println(""+bPunkt.x);
    }
        System.out.println("middle of test");
    for (int i=0;i<p.size();i++){
        System.out.println(""+p.get(i).x);
    }
        System.out.println("end test");

this is what system.out prints :

start test
1
0
1
3
3
5
3
5
5
4
middle of test
4
4
4
4
4
4
4
4
4
4
end test
1
  • 7
    You need to assign a new instance to bPunkt before adding. Commented Mar 8, 2014 at 22:09

1 Answer 1

2

You are modifying the same instance bPunkt and sticking it in the list. So in the end you have a list with the same object over and over in it.

Sign up to request clarification or add additional context in comments.

3 Comments

Next time you feel stuck with such issues, print object references. It really helps.
You can only do that if you do not override toString().
Actually I stand corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.