Adding to unexpected arraylist behavior

I'm not sure what's going on here. Any enlightenment would be greatly appreciated.

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));

      

Output

0
1
2
3
4
5
6
7
8
9

0
1
7
8
2
3
4
5
6
7
8

      

Why does he add in 7 and 8 ... and where is 9?

+3


source to share


2 answers


You get this behavior because you are calling get()

with itself Integer

, contained in 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

      

Change your code to this and you should be fine:



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

      

Output:

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

      

+12


source


You use an extended loop and then print the value with get

; You must either print the values ​​at all indices with get

, or use an extended loop without get

. Better yet, use Arrays.toString

for printing to avoid this kind of confusion:



for(int i = 0; i < 10; i++)
    al.add(i);
Arrays.toString(al);
al.add(2,8);
Arrays.toString(al);

      

+2


source







All Articles