使用set方法时ArrayList <integer>输出错误的结果

时间:2018-12-04 03:21:27

标签: java arraylist

ArrayList<Integer> num = new ArrayList<Integer>();
num.add(0);
num.add(0);
num.add(0);
System.out.println(num.set(1, 2));//I don't know why it's outputting 2's down the
                                  //second column
System.out.println("   0  1  2");
int counter1 = 0;
for(int row : num) {
    System.out.println(counter1 + " " + num);
    counter1 += 1;
}

我需要帮助弄清楚为什么3 x 3数组输出2的向下一列。

1 个答案:

答案 0 :(得分:1)

在每次迭代中,您将打印整个ArrayListnum),而不仅仅是相关元素(row):

for (int row : num) {
    System.out.println(counter1 + " " + row);
    // Here ----------------------------^
    counter1 += 1;
}