I am new to Java. I was reading someone's solution to a question and I encountered this:
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]++;
What do the last two lines do?
This is a for-each loop. It sets p
to the first element of ps
, then runs the loop body. Then it sets p
to the second element of ps
, then runs the loop body. And so on.
It's approximately short for:
for(int k = 0; k < ps.length; k++)
{
int p = ps[k];
counts[p]++;
}
The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
Syntax
for(data_type variable : array | collection){}
Source :Java For Each Loop
In your case this loop is iterating the Array
Equivalent Code without For Each Loop
for (int i=0;i<ps.length;i++){
int p=ps[i];
counts[p]++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With