向arraylist添加内容出现了意外行为

3
我不确定这里发生了什么。非常感谢您提供的启示。
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));

输出

0
1
2
3
4
5
6
7
8
9

0
1
7
8
2
3
4
5
6
7
8

为什么要添加7和8,而9去哪了?

2
如果您在每个for循环中已经有了对整数的引用,为什么还要调用Arraylist.get(i)呢?为什么不只是打印当前的整数i以进行测试呢? - andrewdleach
你的for循环(for (Integer i : al))实际上是foreach循环...它们让你访问集合中的元素;你不需要在循环内部操作集合。换句话说,每个i都是集合内部的一个整数,而不是像第一个(也是唯一的)for循环中的索引。 - D. Ben Knoble
2个回答

12

你之所以遇到这种行为是因为你正在使用 ArrayList 中包含的那些 Integer 对象来调用 get() 方法:

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

请将您的代码更改为以下内容,问题将得到解决:

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

输出:

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

2
您正在使用增强循环,并使用get打印值; 您应该使用get打印所有索引处的值,或者不使用get的增强循环。更好的做法是使用Arrays.toString进行打印,以避免这种混淆:
for(int i = 0; i < 10; i++)
    al.add(i);
Arrays.toString(al);
al.add(2,8);
Arrays.toString(al);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接