添加到arraylist意外的行为

noW*_*ome 3 java arraylist

我不确定这里发生了什么.任何启蒙都会受到高度赞赏.

ArrayList<Integer> al = new ArrayList<>();

for(int i = 0; i < 10; i++)
    al.add(i);

for(Integer i : al)
    System.out.println(al.get(i));

al.add(2,8); //should add the value 8 to index 2? 

System.out.println();
for(Integer i : al)
    System.out.println(al.get(i));
Run Code Online (Sandbox Code Playgroud)

产量

0
1
2
3
4
5
6
7
8
9

0
1
7
8
2
3
4
5
6
7
8
Run Code Online (Sandbox Code Playgroud)

为什么在7和8中加入...... 9在哪里?

Tim*_*sen 12

您正在获取此行为,因为您正在get()使用以下Integer内容中包含的s 进行调用ArrayList:

for (Integer i : al)
    System.out.println(al.get(i));   // i already contains the entry in the ArrayList

al.add(2,8); //should add the value 8 to index 2? 

System.out.println();
for (Integer i : al)
    System.out.println(al.get(i));   // again, i already contains the ArrayList entry
Run Code Online (Sandbox Code Playgroud)

将您的代码更改为此,一切都会好的:

for (Integer i : al)
    System.out.println(i);
Run Code Online (Sandbox Code Playgroud)

输出:

0
1
8    <-- you inserted the number 8 at position 2 (third entry),
2        shifting everything to the right by one
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)