简体   繁体   中英

enhanced for-loop behavior for handling collection object

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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