【发布时间】:2012-12-01 07:55:23
【问题描述】:
在 Android 中编码时,我需要一个 ArrayList of Points,我称之为 wormPt。我是通过循环初始化的。
ArrayList<Point> wormPt = new ArrayList<Point>();
Point pt = new Point();
.
.
.
private void initializeWorm() {
// TODO Auto-generated method stub
pt.x = 220;
pt.y = 300;
for (int i = 0; i <= 5; i++) {
wormPt.add(pt);
Log.d("wormdebug", wormPt.toString());
pt.x -= 5;
}
Log.d("wormdebug", wormPt.toString());
}
我的最后一个 log.d 应该报告点 (220,300) (215,300) (210,300) (205,300) (200,300) (195,300)
相反,我的所有分数都是 (190, 300)
这是我的日志数据
11-21 23:48:11.549: D/wormdebug(3273): [Point(220, 300)]
11-21 23:48:11.600: D/wormdebug(3273): [Point(215, 300), Point(215, 300)]
11-21 23:48:11.600: D/wormdebug(3273): [Point(210, 300), Point(210, 300), Point(210, 300)]
11-21 23:48:11.600: D/wormdebug(3273): [Point(205, 300), Point(205, 300), Point(205, 300), Point(205, 300)]
11-21 23:48:11.600: D/wormdebug(3273): [Point(200, 300), Point(200, 300), Point(200, 300), Point(200, 300), Point(200, 300)]
11-21 23:48:11.600: D/wormdebug(3273): [Point(195, 300), Point(195, 300), Point(195, 300), Point(195, 300), Point(195, 300), Point(195, 300)]
11-21 23:48:11.630: D/wormdebug(3273): [Point(190, 300), Point(190, 300), Point(190, 300), Point(190, 300), Point(190, 300), Point(190, 300)]
11-21 23:48:14.669: W/KeyCharacterMap(3273): No keyboard for id 0
11-21 23:48:14.679: W/KeyCharacterMap(3273): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
我试过了 Can't add element to ArrayList in for loop 和其他人,但他们似乎没有同样的问题。任何帮助将不胜感激。 提前致谢。
【问题讨论】:
-
您似乎错误地认为
wormPt.add()正在克隆pt。
标签: java for-loop arraylist initialization