Assigning fields in a Java foreach declaration

I know that the foreach loop used in the following example does not compile. But does anyone know why using a field in a foreach loop declaration is not allowed?

public class Foo {
    private Object obj;

    public void run(List<Object> objects) {
        for (obj : objects) {
            process();
        }
    }

    private void process() {
        // do something with obj
    }
}
+3
source share
5 answers

I expect there are several reasons, but this probably comes down to preventing a programmer error.

One thing that is confusing is "what would be the value of obj after loop execution"? Unlike the standard for the cycle, the reinforced for each cycle does not try to make guarantees regarding its own mechanics.

, . , , for-each, , , , . , .

obj process()?

+1

,

  • ( )
  • .
+7

, foreach. foreach - , - .

process()... , . , , , this.obj = obj.

+2

obj for ? .

+1

2004 . :

"-", (. JLS 14.14.2). -, . -, , concurrency, . -, , "final". -, , , , , . , . .

+1
source

Source: https://habr.com/ru/post/1768120/


All Articles