I know that the foreach loop used in the following example doesn’t compile. But does anybody know why using a field in a foreach loop declaration isn’t allowed?
public class Foo {
private Object obj;
public void run(List<Object> objects) {
for (obj : objects) {
process();
}
}
private void process() {
// do something with obj
}
}
I expect there are a few reasons, but it probably just comes down to preventing programmer error.
One thing that would be confusing is “what would be the value of obj after the loop had executed”? Unlike the standard for-loop, the enhanced for-each loop isn’t trying to make guarantees about its own mechanics.
Another thing is that instance fields represent an object’s state. What you’d be saying by using an instance field in a for-each loop is that the object could changes from one state, then to one or many intermediate states, then to final a state during the course of a single operation. That’s just bad design, and worth preventing.
Why not pass obj as an argument to
process()?