Does the "values ()" method run with each iteration of the loop, or does it run only once?
for(String s : values()) { //doSmth }
In order to show you the essence, I made such a class. If you run it, you will see that the string "x 1" is displayed (from the method), and only after it the others (already from the cycle) will appear - "1", "1", "1". That is, we experimentally proved that the method for obtaining a collection is called only once - at the beginning.
static int x=0; public static void main(String[] args){ for(Integer s : returnCollection(x)) { System.out.println(s); //выводится в цикле } } static ArrayList<Integer> returnCollection(int x){ x++; System.out.println("x "+x); // выводится при вызове метода ArrayList<Integer> r = new ArrayList<>(Arrays.asList(x,x,x)); return r; }
Source: https://ru.stackoverflow.com/questions/980833/
All Articles
values()
returns a reference to theIterable
object. He will call theiterator()
method, which will return a reference to theIterator
. Well, and rushed -hasNext()
-next()
or whatever you need ... - Олексій Моренець