Reputation: 32158
I have a boolean array
boolean[] test = {
false,
true,
true,
false,
true
};
and I'm trying to flip (true to false, and false to true) the values with "for-each" statement like so:
for(boolean x : test) {
x = !x;
}
But it's only changing the x
variable in the local scope.
I'm new to Java and I want to ask how this could be done and if this is the right approach. I've searched a lot, but most of the examples are used to collect data from the array without modifying it.
Upvotes: 1
Views: 10672
Reputation: 3163
No surprises that it does not work. You are manipulating a local variable after all and its not an object and not a reference. Use a normal for loop and modify corresponding position.
Upvotes: 1
Reputation: 10974
You will need to use a non-enhanced for loop if you want affect the values of test:
for (int i = 0; i < test.length; ++i) {
test[i] = !test[i];
}
Upvotes: 2
Reputation: 8582
You don't do that with a for each, as the for each reads the value of the array, and stores it in a local variable, as you said. You need to iterate the array and access the index directly. I won't post any code so you can find and think about it.
Upvotes: 1
Reputation: 299
The enhanced for loop is creating a new variable x and setting the value locally each time because boolean is a primitive and is therefore not passed by reference. For this, you will need to use the old for loop.
Upvotes: 0
Reputation: 1500225
No, that's not the right approach. The enhanced for loop doesn't let you change the values of what you're iterating over. To invert the array, you'd want to use a regular for loop:
for (int i = 0; i < test.length; i++) {
test[i] = !test[i];
}
(Note that the enhanced for loop would let you make changes to the objects which any array elements referred to, if they were classes - but that's not the same thing as changing the value of the element itself.)
Upvotes: 9
Reputation: 108947
You cannot change the item in a for-each loop. Can you use a regular loop instead?
for (int i=0; i < test.length; i++)
{
test[i] = !test[i];
}
Upvotes: 1