我是Java的新手。我在阅读别人对一个问题的解决方案时遇到了这个:
int[] ps = new int[N];
for (int i = 0; i < N; i++)
ps[i] = input.nextInt();
int[] counts = new int[1005];
for (int p : ps)
counts[p]++;
最后两行代码的作用是什么?
这是一个for-each循环。它将p
设置为ps
的第一个元素,然后运行循环体。接着它将p
设置为ps
的第二个元素,再运行循环体。以此类推。
它大致相当于:
for(int k = 0; k < ps.length; k++)
{
int p = ps[k];
counts[p]++;
}
在Java5中引入了for-each循环。它主要用于遍历数组或集合元素。for-each循环的优点是它消除了错误的可能性,并使代码更易读。
Syntax语法:
for(data_type variable : array | collection){}
在您的情况下,该循环正在迭代Array
无 for each 循环的等效代码
for (int i=0;i<ps.length;i++){
int p=ps[i];
counts[p]++;
}
p
不是索引,而是数组 ps
的元素。 - singhakash该行代码正在迭代数组中的每个索引,并将其值按照顺序存储到变量p
中。您可以通过检查进行确认。
for (int p : ps){ // if ps is {1,2,3}
System.out.print(p+" "); // it will print 1 2 3
counts[p]++;
}
这是一个for循环。 for (int p : ps)
遍历 ps
int数组中的整数
p
范围在数组ps
上。你可以稍微尝试一下,看看它是如何工作的,例如在循环中打印p
的值。 - Juho