大家.
我刚刚进入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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
首先,其他几个答案都具有误导性和/或不正确性.请注意,数组是一个对象.因此,无论数组本身是否包含基本类型或对象引用,您都可以将它们用作列表中的元素.
接下来,声明一个变量,List<int[]> list而不是声明它ArrayList<int[]>.这使您可以轻松地更改List为一个LinkedList或一些其他实现,而不会破坏其余代码,因为它保证仅使用List接口中可用的方法.有关更多信息,您应该研究"编程到界面".
现在回答你的真实问题,这个问题只是作为评论添加的.我们来看几行代码:
Integer[] point = new Integer[3];
Run Code Online (Sandbox Code Playgroud)
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);
//...
}
Run Code Online (Sandbox Code Playgroud)
在这里,您可以为数组的元素指定值,然后将数组的引用添加到您的数组中List.每次循环迭代时,都会将新值分配给同一个数组,并将另一个引用添加到同一个数组中List.这意味着对已经重复写入的相同数组List有10个引用.
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(); }}
现在这个循环打印出相同的数组 10次.数组中的值是在上一个循环结束时设置的最后一个值.
要解决此问题,您只需确保创建10个不同的阵列.
最后一个问题:如果您声明it为Iterator<Integer[]> it(或Iterator<int[]> it),则不需要转换返回值it.next().事实上,这是首选,因为它是类型安全的.
最后,我想问一下int每个数组中的s代表什么?您可能希望重新访问程序设计并创建一个包含这三个ints 的类,可以是数组,也可以是三个成员变量.