Reputation: 4884
In my Android App I have simple C-like 'for loops' like this:
for (int i = 0; i < max_count; i++) {
// I must use the value of 'i' in the for loop body
}
But the Android studio gives me a Lint warning, suggesting to change the for loop to a foreach loop.
Can you tell me how can I switch to foreach loop and use 'i' variable in the body of the loop?
Upvotes: 4
Views: 2129
Reputation: 21
If you're iterating over an array, the foreach construct means you do not need an array index.
So, for example:
int[] myArrayValues = new int[4];
// code to fill up array ...
for (int specificValue : myArrayValues) {
// specific value is a value from the array, do something useful with it
}
In this case, specificValue is equal to myArrayValues[0] on the first iteration through the loop, then myArrayValues[1], myArrayValues[2] and finally myArrayValues[3] as the loop iterates.
Notes that in the answer above, although there is a variable i, it's not an index at all and will contain the vales in the array (in that case, they're all 0 until the array is filled with values).
So, for example to sum the values in the array, we can do something like this:
int[] items = new int[3];
items[0] = 3;
items[1] = 6;
items[2] = 7;
int sum = 0;
for( int value : items ) {
sum += value;
}
// at this point sum = 16
Think of it as "for each value in items"
Upvotes: 1
Reputation: 15821
foreach
construction is not applicable to int.
foreach
works only with arrays and collections.
For alternative you can use :
int max = 5;
int[] arr = new int[max];
for (int i : arr) {
}
Docs :
The enhanced for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array/collection without explicitly expressing how one goes from element to element.
Upvotes: 4
Reputation: 740
If you have to make use of the counter variable within the loop, it doesn't make sense to switch to using a for each
-- essentially, the linter may be wrong here.
If you do want to change it nevertheless, you need to define the counter outside the for each
as follows:
int i = 0; // your counter, now defined outside of the loop -- but still usable inside
for ( SomeItem e : SomeIterableObj ) { // the for-each loop
// do something with the element, 'e'
// do something with the counter, 'i'
i++; // or manipulate the counter in whichever way you need to.
}
This way, you're using a for each
loop and you still get to make use of a counter.
Upvotes: 3