2

I changed the list reference and point it to the whole new list while iterating over it but it still prints the old value.

This may seems incorrect , why anyone wants to change the list itself reference itself while iterating over it but iteration is going on and some another functionality changes the reference itself or create new object and assign it to the original list.

for (String s : lst) {
 System.out.println("list is:"+lst);
 System.out.println(s);
 lst = lst1;
}

This still prints the old list after one iteration.

2 Answers2

0

for loop in this case implicitly operates with list's iterator, not the list. So, changing list's link has no effect, you are still implicitly using old iterator.

See this The For-Each Loop, and this How does the Java for each loop work?

Community
  • 1
  • 1
Alexey
  • 1,198
  • 1
  • 15
  • 35
0

In a for-each loop, for the first iteration itself the iterator for the list is obtained. This is because of internal handling mechanism of the for-each loop, which is defined during the compilation itself. So if you just assign the list reference with a new instance it is not going to affect the iterator.

Loganathan
  • 903
  • 2
  • 10
  • 23