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
Don Roby
  • 40,677
  • 6
  • 91
  • 113

1 Answers1

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.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94