Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does for(int i : x) do? [duplicate]

Tags:

java

for-loop

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?

like image 314
ksraj98 Avatar asked Apr 12 '15 10:04

ksraj98


2 Answers

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]++;
}
like image 129
user253751 Avatar answered Oct 18 '22 14:10

user253751


For-each loop (Advanced or Enhanced For loop):

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]++;
}

        
like image 37
Neeraj Jain Avatar answered Oct 18 '22 15:10

Neeraj Jain