ktm5124
ktm5124

Reputation: 12123

Placing a function call in a for loop

I have a function that looks a lot cleaner this way:

public static List<Integer> permuteDigits(int number) {
    List<Integer> permutations = new ArrayList<>();

    for (String s : permutations(String.valueOf(number))) 
        permutations.add(Integer.parseInt(s));

    return permutations;
}

But you can see, there's a function call inside the for-each loop. I'm pretty sure that the compiler doesn't do this, but... the function isn't called on each iteration of the for loop, is it?

I'm almost positive this isn't the case, but I just wanted to make sure. That is to say, the above code is no less efficient than the following:

public static List<Integer> permuteDigits(int number) {
    List<String> strPerms = permutations(String.valueOf(number));
    List<Integer> permutations = new ArrayList<>();

    for (String s : strPerms) 
        permutations.add(Integer.parseInt(s));

    return permutations;
}

Correct?

Upvotes: 3

Views: 48

Answers (2)

Anderson Vieira
Anderson Vieira

Reputation: 9049

In your first code block, permutations(String.valueOf(number)) will be called once, return its result, and then the for loop will iterate through the elements in the result. Like in the example below:

static List<Integer> createNumbers() {
    System.out.println("createNumbers");
    return Arrays.asList(0, 1, 2);
}

public static void main(String[] args) {
    for (Integer num : createNumbers()) {
        System.out.println(num);
    }
}

The result shows that createNumbers() was called only once:

createNumbers
0
1
2

Upvotes: 1

GlobalVariable
GlobalVariable

Reputation: 181

Yes, that is correct. Condition in the for-each loop is evaluated only once.

Upvotes: 1

Related Questions