Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a for-each loop work? [duplicate]

How does a for-each loop works when it calls a method, either recursively or a different method?

Example:

for(String permutation : permute(remaining))
    {   

      // Concatenate the first character with the permutations of the remaining chars
      set.add(chars.charAt(i) + permutation);
    }

By the way the method permute takes in a String and returns a set.

Thank you.

like image 824
user1965283 Avatar asked Jan 10 '13 02:01

user1965283


People also ask

What is a for each loop in Java?

In this tutorial we are going to learn about Java For Each loop working in detail. The for-each loop, added in Java 5 (also called the “enhanced for loop”), is equivalent to using a java.util.Iterator—it’s syntactic sugar for the same thing.

What is “for each” loop in C++?

Apart from the generic looping techniques, such as “for, while and do-while”, C++ in its language also allows us to use another functionality which solves the same purpose termed “for-each” loops. This loop accepts a function which executes over each of the container elements. This loop is defined in the header file “algorithm”, ...

What is an example of a simple for loop?

For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element. There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.

How do I loop through an array of elements?

There is also a " for-each " loop, which is used exclusively to loop through elements in an array: The following example outputs all elements in the cars array, using a " for-each " loop: Note: Don't worry if you don't understand the example above.


1 Answers

According to the Java Language Specification for the enhanced for statement, the expression:

for ( FormalParameter : Expression ) Statement

Is executed as follows:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

Thus, the Expression (which must be of type Iterable) only has its iterator() method called once.

like image 168
ulmangt Avatar answered Oct 07 '22 14:10

ulmangt