繁体   English   中英

添加到arraylist意外的行为

[英]Adding to arraylist unexpected behavior

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

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在哪里?

您正在获得此行为,因为您使用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

您正在使用增强型循环,然后使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM