Does the "values ​​()" method run with each iteration of the loop, or does it run only once?

for(String s : values()) { //doSmth } 
  • 2
    values() returns a reference to the Iterable object. He will call the iterator() method, which will return a reference to the Iterator . Well, and rushed - hasNext() - next() or whatever you need ... - Олексій Моренець

1 answer 1

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; }