我可以使用 for each 语法从数组中读取数据:
int[] a = new int[100];
for (int i = 0; i < 100; i++){
a[i] = i;
}
for (int element : a){
System.out.println(element);
}
但是否可以同样填充数组。比如说,使用 i*2
值?
我没有发明这样的方法,我宁愿问你我是否错了。
最佳答案
来自 Java Docs ,
The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each
loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would
cover the great majority of cases.
所以,简单来说,不可能填充数组。
关于java - 对于每个循环 : can we populate an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169703/