循环中ArrayList的初始化错误

Rya*_*yan 1 java for-loop initialization arraylist

在Android中编码时,我需要一个我称之为wormPt的PointsList.我通过循环初始化它.

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());
}
Run Code Online (Sandbox Code Playgroud)

我的上一次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
Run Code Online (Sandbox Code Playgroud)

我试过 无法在for循环和其他方面向ArrayList添加元素,但它们似乎没有同样的问题.任何帮助将不胜感激.提前致谢.

Jon*_*eet 5

问题是您ArrayList包含对同一对象的多个引用.你在循环中所做的就是添加相同的引用并改变对象.

如果更改循环以在每次迭代时创建一个新的 Point循环,它将起作用:

int x = 220;
for (int i = 0; i <= 5; i++) {
    wormPt.add(new Point(x, 300));
    x -= 5;
}
Run Code Online (Sandbox Code Playgroud)

理解变量,对象引用之间的区别非常重要.pt是一个变量.它的值是Point对象的引用.除非您要求新对象,否则Java不会为您创建一个.例如:

Point a = new Point(10, 20);
Point b = a; // Copies the *reference*
a.x = 100;
System.out.println(b.x); // 100
Run Code Online (Sandbox Code Playgroud)

请注意,这并不是将a和b 变量相互关联 - 它只是给它们相同的值(相同的引用).因此,您可以稍后更改a为对不同的引用Point,并且不会更改b:

Point a = new Point(10, 20);
Point b = a; // Copies the *reference*
a.x = 100;
a = new Point(0, 0); // This doesn't affect b, or the object its value refers to
System.out.println(b.x); // 100
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这有点像给10个不同的人一张纸,上面有你的家庭住址.如果其中一个人访问该地址并将前门涂成绿色,那么他们中的另一个访问该地址,他们将看到一个绿色的前门.