Reputation: 61
Why doesn't this work ie assign each element in the array to 1?
int []iA2 = new int[10];
System.out.println(iA2[0]); //0
for (int place:iA2){
place=1;
}
System.out.println(iA2[1]); // prints 0
Upvotes: 0
Views: 22
Reputation: 11209
The values from iA2 are being assigned to variable place
. You then modify the value of place
.
What you should do:
for (int i=0; i<iA2.length; i++)
iA2[i] = 1;
Note that if you were dealing with objects such as an instance of a Vehicle class you could iterate and change instance variables.
for (Vehicle v: vehicles)
v.speed = 10;
This works because v
is being assigned a reference to an object unlike what happens in the case of primitive types such as int.
Upvotes: 1