我正在尝试编写一个简单的游戏,让敌人在网格上追逐玩家。我正在使用维基百科寻路页面中的简单算法进行寻路。这涉及创建两个列表,每个列表项包含 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();
}
}
}
最佳答案
首先,其他几个答案具有误导性和/或不正确。请注意,数组是一个对象。因此,您可以将它们用作列表中的元素,无论数组本身是否包含基本类型或对象引用。
接下来,声明一个变量为List<int[]> list
优于将其声明为 ArrayList<int[]>
.这使您可以轻松更改 List
到 LinkedList
或其他一些实现而不会破坏其余代码,因为它保证只使用 List
中可用的方法界面。有关详细信息,您应该研究“界面编程”。
现在回答您真正的问题,该问题仅作为评论添加。让我们看一下您的几行代码:
Integer[] point = new Integer[3];
这一行创建了一个数组 Integer
s,显然。
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);
//...
}
在这里,您为数组的元素赋值,然后将对数组的引用添加到您的List
。 .每次循环迭代时,您都将新值分配给同一数组,并将对同一数组的另一个引用添加到List
.这意味着 List
有 10 个引用 对同一个数组 已被重复覆盖。
迭代器it = list.iterator(); while (it.hasNext()) { point = (Integer[])it.next(); 对于 (int i = 0; i < 3; i++) { System.out.print(point[i] + ","); } System.out.println(); }
现在这个循环打印出 相同的数组 10 次。数组中的值是上一次循环结束时最后设置的值。
要解决此问题,您只需确保创建 10 个不同数组即可。
最后一期:如果你声明it
作为Iterator<Integer[]> it
(或 Iterator<int[]> it
),您不需要转换 it.next()
的返回值.事实上,这是首选,因为它是类型安全的。
最后想问一下int
是什么每个数组中的s代表?您可能想重新审视您的程序设计并创建一个包含这三个 int
的类s,可以是一个数组,也可以是三个成员变量。
关于java - 整数数组的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665188/