Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field assignment in a Java foreach declaration

Tags:

java

foreach

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
    }
}
like image 557
kraftan Avatar asked Sep 14 '25 14:09

kraftan


2 Answers

Probably because it

  • limits the scope of the loop variable (thus making the code clearer, and avoiding possible subtle bugs), and
  • simplifies parsing for the compiler.
like image 130
Péter Török Avatar answered Sep 17 '25 04:09

Péter Török


It generally doesn't make sense to assign to a field in a foreach loop. The scope of an object in a foreach loop is just the one iteration of the loop, whereas the scope of a field is the lifetime of the object.

You should really just pass each object as an argument to process()... you wouldn't be gaining anything by storing the reference as a field. Plus, if you really really want to you can just manually assign to a field using this.obj = obj.

like image 37
ColinD Avatar answered Sep 17 '25 03:09

ColinD