在我的Android应用程序中,我有像这样简单的类似C的'for循环':
for (int i = 0; i < max_count; i++) {
// I must use the value of 'i' in the for loop body
}
但Android工作室给了我一个Lint警告,建议将for循环更改为foreach循环。
你能告诉我如何切换到foreach循环并在循环体中使用'i'变量?
答案 0 :(得分:4)
foreach
构造不适用于int。
foreach
仅适用于数组和集合。
如需替代方案,您可以使用:
int max = 5;
int[] arr = new int[max];
for (int i : arr) {
}
Docs:
增强的for循环是5.0版本中Java SE平台引入的一个流行功能。它的简单结构允许通过呈现访问数组/集合的每个元素的for循环来简化代码,而无需明确表示从元素到元素的方式。
答案 1 :(得分:3)
如果你必须在循环中使用计数器变量,切换到使用for each
是没有意义的 - 实质上,这里的linter可能是错误的。
如果您确实想要更改它,则需要在for each
之外定义计数器,如下所示:
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.
}
这样,您就可以使用for each
循环,但仍然可以使用计数器。
答案 2 :(得分:1)
如果你在迭代数组,foreach结构意味着你不需要数组索引。
所以,例如:
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
在这种情况下,在循环的第一次迭代中,specificValue等于myArrayValues [0],然后是myArrayValues [1],myArrayValues [2],最后是循环迭代的myArrayValues [3]。
请注意,在上面的答案中,尽管存在变量i,但它根本不是索引,并且将包含数组中的值(在这种情况下,它们都是0,直到数组填充了值)。
因此,例如,为了对数组中的值求和,我们可以这样做:
.625
将其视为“项中的每个值”