每个人。
我刚接触Java,我正在尝试编写一个简单的游戏,其中敌人在网格上追逐玩家。我正在使用来自维基百科寻路页面的简单算法进行寻路。这涉及创建两个列表,每个列表项包含 3 个整数。这是我正在尝试构建和显示这样一个列表的测试代码。
当我运行以下代码时,它会为 ArrayList 中的每个数组打印出相同的数字。为什么这样做?
public class ListTest {
public static void main(String[] args) {
ArrayList<Integer[]> list = new ArrayList<Integer[]>();
Integer[] point = new Integer[3];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
point[j] = (int)(Math.random() * 10);
}
//Doesn't this line add filled Integer[] point to the
//end of ArrayList list?
list.add(point);
//Added this line to confirm that Integer[] point is actually
//being filled with 3 random ints.
System.out.println(point[0] + "," + point[1] + "," + point[2]);
}
System.out.println();
//My current understanding is that this section should step through
//ArrayList list and retrieve each Integer[] point added above. It runs, but only
//the values of the last Integer[] point from above are displayed 10 times.
Iterator it = list.iterator();
while (it.hasNext()) {
point = (Integer[])it.next();
for (int i = 0; i < 3; i++) {
System.out.print(point[i] + ",");
}
System.out.println();
}
}
}