Field assignment in Java foreach declaration
I know that the foreach loop used in the following example cannot be compiled But does anyone know why fields are not allowed in foreach loop declarations?
public class Foo { private Object obj; public void run(List<Object> objects) { for (obj : objects) { process(); } } private void process() { // do something with obj } }
Solution
I hope there are several reasons, but it may just be to prevent programmer errors
One puzzling thing is "what is the value of obj after loop execution"? Unlike the standard for loop, the enhanced for - each loop does not attempt to guarantee its own mechanism
Another thing is that the instance field represents the state of the object By using the instance field in the for each loop, you mean that objects can change from one state to one or more intermediate states, and then to the final state during a single operation It's just a bad design and worth preventing
Why not pass obj as a parameter to process ()?