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
}
}
Probably because it
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With