Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
ktm5124 Avatar asked Apr 15 '26 13:04

ktm5124


2 Answers

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
like image 172
Anderson Vieira Avatar answered Apr 17 '26 01:04

Anderson Vieira


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

like image 40
GlobalVariable Avatar answered Apr 17 '26 02:04

GlobalVariable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!