Reputation: 157
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.
Upvotes: 3
Views: 73
Reputation: 45742
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.
Upvotes: 3
Reputation: 7165
This is because, enhanced for loop uses iterator. So changing the reference will not have any impact. You can check different scenarios here
Upvotes: 0
Reputation: 393801
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);
}
Upvotes: 6