3

I'm not sure what is 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 is it adding in 7 and 8...and where did 9 go?

2
  • 2
    If you already have a reference to the Integer in each for loop why are you calling Arraylist.get(i)? why not just print the current Integer i for testing? Commented Jun 22, 2015 at 2:11
  • your for loops (for (Integer i : al)) are really foreach loops... they give you access to the elements of a collection; you don't need to touch the collection within the loop. In other words, each i is an integer from inside the collection, not an index like in the first (and only) for loop Commented Jun 22, 2015 at 2:13

2 Answers 2

12

You are getting this behavior because you are calling get() using the very Integers contained in the 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 all will 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
Sign up to request clarification or add additional context in comments.

Comments

2

You are using the enhanced loop, and then printing the value using get; You should either print values at all indexes with get, or use enhanced 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.