1

What's the best way to iterate over an array returned by a function?

Example:

for (String s : collectMyStrings()){
  System.out.println(s);
}

Is collectMyStrings() called in each iteration, or does Java only call it once, and use the returned array for all iterations of the for loop?

3
  • 5
    You could answer your own question by just trying it! Commented Mar 21, 2012 at 20:54
  • Yes, but I like to have it documented, if others try google, like i did Commented Mar 21, 2012 at 20:54
  • if you were really concerned you could always save it as a variable and then loop over the variable. But I think it will only call it once. Commented Mar 21, 2012 at 20:55

3 Answers 3

7

It will be called only once, and an iterator for the returned array will be created (implicitly).

Sign up to request clarification or add additional context in comments.

2 Comments

For arrays, the compiler transforms the for-each loop into an ordinary for loop with an index variable. Only for-each loops on Iterable objects are transformed to the Iterator-based loop.
Just to add a bit more context to this. I believe that you can't/shouldn't modify what is being iterated over. So it would make sense for the compiler to cache off the returned iterable.
2

For arrays, the for-each loop is transformed by the Java compiler into an ordinary for loop with an index variable. That means that your code snippet is roughly equivalent to the this:

String[] strings = collectMyStrings();
int length = strings.length;

for (int i = 0; i < length; i++) {
    String s = strings[i];
    System.out.println(s);
}

So, as you can see, the method is called only once. Even the length property of the array is read only once.

Comments

0

The method collectMyStrings() is only called once to get the array/collection to iterate over.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.