5

我可以使用每种语法从数组中读取数据:

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价值观?
我没有发明这样的方法,宁愿问你我是否错了。

4

6 回答 6

7

From Java Docs,

The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-eachloop 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 wouldcover the great majority of cases.

So, in simple words, its not possible to populate arrays.

于 2013-08-11T07:31:53.117 回答
3

目前尚不清楚您要达到的目标。增强的 for 循环只能遍历集合 - 在您的情况下,您在集合中没有有用的值开始 - 只有您尝试填充的集合。

如果您只是想根据一些基于现有集合的计算来填充一个数组,那么增强的 for 循环就没有帮助。

即使您确实想根据另一个集合填充数组,使用增强的 for 循环也不理想,因为您没有任何索引的概念。例如,如果你有一个String数组并且你想int用字符串的长度填充一个数组,你可以这样做:

String[] words = ...; // Populate the array
int[] lengths = new int[words.length];

int index = 0;
for (String word : words) {
    lengths[index++] = word.length();
}

...但这并不理想。当然,如果您要填充 a 会更好List,因为您可以调用add

String[] words = ...; // Populate the array
List<Integer> lengths = new ArrayList<Integer>(words.length);

for (String word : words) {
    lengths.add(word.length());
}
于 2013-08-11T07:24:53.787 回答
2

不,这是不可能的。您必须使用 for 的第一个版本。

于 2013-08-11T07:24:17.233 回答
1

当前索引没有计数器,只有 foreach 循环中索引处的值,因此不可能。

于 2013-08-11T07:25:13.750 回答
1

不可能为每个循环的增强中使用的实际数组分配值。这是因为增强的 for-each 循环不允许您访问数组的指针。为了改变数组的值,你必须从字面上说:

a[i] = anything

但是,您可以使用增强的 for 循环将值分配给另一个数组,如下所示:

int[] nums = new int[4];
int[] setNums = {0,1,2,3};
i = 0;
for(int e: setNums) {
   nums[i++] = e*2;
}

Java 中增强的 for 循环仅提供了一点语法糖来获取数组或列表的值。在某些方面,它们的操作类似于将对象传递给方法——传递给方法的原始对象不能在方法中重新分配。例如:

int i = 1;
void multiplyAndPrint(int p) {
  p = p*2;
  System.out.println(p);
}
System.out.println(i);

将打印 2,然后打印 1。这与您尝试从 for-each 循环分配值时遇到的问题相同。

于 2013-08-11T07:34:50.687 回答
1

为此,您需要一种方法来获取数组中“元素”的索引。

如何在Java中找到数组中元素的索引?有很多关于如何做到这一点的建议。

于 2013-08-11T07:35:08.617 回答