Wednesday Nov 08, 2006
Wednesday Nov 08, 2006
I want to talk about the enhanced for ('foreach') loop, an immensely popular construct. Many people are surprised to find that it only accepts Iterable expressions (and arrays, which I'll ignore). Why not also Iterators?
The JSR201 Expert Group considered this issue at length. foreach is syntactic sugar; the compiler generates an iterator() and a loop variable and a basic for loop in its place. The primary reason against passing an Iterator to foreach is that the user-provided body could modify it during iteration, and so break the compiler's assumptions about its generated code:
Iterator i = myList.iterator();
for (Object o : i) { /* Maybe I'll just call i.remove() here, it'll be fun */ }
By requiring Iterables, JSR201 essentially placed safety above raw functionality. But even with Iterables, user code can still interfere with the compiler's code. A Collection passed to foreach can be modified concurrently and most Collection implementations aren't synchronized internally, so the compiler-generated iterator could break.
So, given that interference is possible with Iterables, and given that using Iterators would be very convenient, maybe we should dial down the safety a little to add some functionality. I'm not proposing any changes now, but I am keeping an open mind on Iterators. I control for the fact that people who want Iterator support shout the loudest 
(The argument against interference from user code is also why the loop variable isn't visible. This decision is very sensible.)
Posted by Tim Vernum on November 08, 2006 at 10:54 PM PST #
Posted by Matthias Ernst on November 09, 2006 at 01:42 AM PST #
for ( Object o : myList ) { for:remove(o); }Posted by Julius Davies on November 09, 2006 at 10:54 AM PST #
Posted by George on November 15, 2006 at 03:44 AM PST #
Posted by Luis Eduardo V. Matta on November 26, 2006 at 05:58 AM PST #