-2
for (int u: adjList.get(v))
{ 
    instructuion 
}

While processing an algorithm, I came across this Java syntax of the "For" loop that I can't figure out. I know that usually it is used like this:

for (int i=0; i < 6; i++) {
    instructuion 
}

What intrigues me here is the ":" in int u: adjList.get(v). I know perfectly well that adjList is a list and u a variable of type integer.

I searched many sites, but none of them gave details on this syntax.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
kirilinko
  • 1
  • 2

2 Answers2

0

The syntax "for-each loop" is used to iterate over a collection of items. In this example, the loop is saying: "for each item of type int in the list adjList.get(v), execute the instruction". It is equivalent to writing a traditional for loop like the one you provided.

For example, the following code will print out the items in the list adjList.get(v):

for (int u: adjList.get(v)) {
    System.out.println(u);
}
vmicrobio
  • 331
  • 1
  • 2
  • 13
0

Yes it is called for-each loop. Let me give you an easy example In the code below we mean that, for each number inside the numbers array.

int numbers[]={33,3,4,5}
// for each number inside the numbers array
for(int number : numbers){
   System.out.println(number);
}