For exactly the same reason that this doesn't work:
Integer a1 = null;
Integer a2 = a1;
a2 = new Integer(1);
System.out.println(a1.toString()); // Fails, a1 is still null
The xx
in your loop is not some kind of reference to the array element; instead, it's a variable that contains a copy of the value of the array element (which is null
in your case). Setting the value of xx
just sets its value, it has no effect whatsoever on the array entry.
Let's follow your code through:
Integer[] x = new Integer[1];
In memory, we now have something like this (ignoring some details):
+−−−−−−−−−−−+
x[Ref22135]−−−−−>| Integer[] |
+−−−−−−−−−−−+
| length: 1 |
| 0: null |
+−−−−−−−−−−−+
(That "Ref22135" inside x
is a value called an object reference, telling the JVM where the array is in memory. Object references are values, like primitives are. The fact we're dealing with objects is actually irrelevant to why setting xx
doesn't affect x[0]
, but since you're using Integer[]
, I have to mention it.)
Now, we enter your loop:
for (Integer xx : x) {
At this point, again ignoring some details, we have:
+−−−−−−−−−−−+
x[Ref22135]−−−−−>| Integer[] |
+−−−−−−−−−−−+
| length: 1 |
| 0: null |
+−−−−−−−−−−−+
xx[null]
The value of x[0]
(null
) has been copied to xx
.
Now we do your assignment:
xx = new Integer(1);
Which gives us:
+−−−−−−−−−−−+
x[Ref22135]−−−−−>| Integer[] |
+−−−−−−−−−−−+
| length: 1 |
| 0: null |
+−−−−−−−−−−−+
+−−−−−−−−−−−−−+
xx[Ref99845]−−−−>| Integer |
+−−−−−−−−−−−−−+
| rawValue: 1 |
+−−−−−−−−−−−−−+
As you can see, setting the value that's in xx
("Ref99845", a reference to the new Integer
object) has no effect whatsoever on the array.
Note that this has nothing to do with the fact we're dealing with objects, it would be exactly the same if we were dealing with primitives:
int[] array = new int[1];
for (int entry : array)
{
entry = 42;
System.out.println(entry);
}
System.out.println(array[0]);
Output:
42
0
If we stop that code at this point:
int[] array = new int[1];
for (int entry : array)
{
entry = 42;
What we have in memory looks something like:
+−−−−−−−−−−−+
array[Ref56418]−−−−−>| int[] |
+−−−−−−−−−−−+
| length: 1 |
| 0: 0 |
+−−−−−−−−−−−+
entry[42]
The only difference when we use Integer[]
is that the value being copied from x[0]
to xx
is an object reference rather than an int. But it doesn't matter; it's still a value, and values are always copied when assigned from one thing to another. (Copying an object reference just copies the reference, of course, not the object it refers to).