Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change from for to foreach in this case?

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?

like image 271
Ehsan Avatar asked Feb 10 '23 07:02

Ehsan


2 Answers

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.

like image 164
Sergey Shustikov Avatar answered Feb 11 '23 19:02

Sergey Shustikov


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.

like image 41
Chris Sprague Avatar answered Feb 11 '23 20:02

Chris Sprague