Is the scope of the enhanced for loop (EFL) variable different for different classes in Java?
When I use an EFL over an ArrayList
containing Integer
s I cannot modify their values directly, however if I do the same thing for an ArrayList
of SimpleObject
s, defined in my code below, I can change the values of the instance variables with no problem.
import java.util.ArrayList;
class SimpleObject{
public int x;
public SimpleObject() {
this.x = 0;
}
}
public class Simple {
public static void main(String args[]){
// Create an arraylist of Integers and SimpleObjects
ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<SimpleObject> soList = new ArrayList<SimpleObject>();
// Add some items to the arraylists
intList.add(1);
intList.add(2);
soList.add(new SimpleObject());
soList.add(new SimpleObject());
// Loop over the arraylists and change some values
for (Integer _int : intList) {
_int = 3; // Why doesn't this work but so.x = 5 below does?
}
for(SimpleObject so : soList) {
so.x = 5;
}
// Loop over the arraylists to print out values
for (Integer _int : intList) {
System.out.println("integer = " + _int);
}
for(SimpleObject so : soList) {
System.out.println(" x = " + so.x);
}
}
}
Actual output:
integer = 1
integer = 2
x = 5
x = 5
Expected output:
integer = 3
integer = 3
x = 5
x = 5
so my question is why doesn't _int = 3;
persist in the first EFL, but so.x = 5;
does in the second EFL?