3

As I am learner of Java.. I came across the following code

public static void main(String[] args) {
  ArrayList<String> a = new ArrayList<>();
  a.add("1");
  a.add("2");
  for(String str: a){
  a = new ArrayList<>();
  System.out.println(str);
  }
 }

I guessed the answer to be

1 null (since the reference is now pointing another object)

but the answer is

1 2

I am unable understand the behavior of enhanced for loop here.

Namrata Shukla
  • 157
  • 2
  • 8

3 Answers3

6

The enhanced for loop creates an Iterator to iterate of the elements of your ArrayList. Changing the a reference to refer to a new ArrayList doesn't affect the Iterator that was created by the loop.

Your loop is equivalent to

Iterator<String> iter = a.iterator();
while (iter.hasNext()) {
    String str = iter.next();
    a = new ArrayList<>();
    System.out.println(str);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
3

When you run

for(String str: a)

It gets an iterator from a, then iterates using that iterator. Reassigning a after it has the iterator will have no effect since it isn't using the a reference, it's using the iterator that a returned when the loop started.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

This is because, enhanced for loop uses iterator. So changing the reference will not have any impact. You can check different scenarios here

Vikas
  • 6,868
  • 4
  • 27
  • 41