How to change this for foreach in this case?

In my Android application, I have a simple C-like for loops:

for (int i = 0; i < max_count; i++) { // I must use the value of 'i' in the for loop body } 

But Android studio gives me a Lint warning, suggesting that I change the for loop to a foreach loop.

Can you tell me how I can switch to the foreach loop and use the variable "i" in the body of the loop?

+4
source share
3 answers

If you need to use the counter variable in a loop, it makes no sense to switch to using for each - essentially, there may be an incorrect linter here.

If you want to change it nonetheless, you need to define a counter outside 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 use a for each loop, and you can still use a counter.

+3
source
Design

foreach not applicable to int.

foreach only works with arrays and collections.

For an alternative, you can use:

 int max = 5; int[] arr = new int[max]; for (int i : arr) { } 

Documents :

Improved for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows us to simplify the code by presenting for-loops that visit each element of the array / collection, without explicitly expressing how one goes from element to element.

+4
source

If you iterate over an array, the foreach construct means you don't need the index of the array.

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] when the loop repeats.

Note that in the answer above, although there is a variable i, it is not an index at all and will contain the vales values ​​in the array (in this case, they are all 0 until the array is filled with values).

So, for example, to summarize the values ​​in an 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 the elements"

+1
source

All Articles