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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With