Using for-each loop in java

java

Solution

No, this loop:

for(City city : country.getCities())

will only call `country.getCities()` once, and then iterate over it. It doesn't call it for each iteration of the loop. In your case it's equivalent to:

for (Iterator<City> iterator = country.getCities().iterator();
     iterator.hasNext(); ) {
    City city = iterator.next();
    // do some operations
}

There's no benefit in rewriting it as per your second snippet.

See section 14.14.2 of the JLS for more details.

Problem

In my code, ``` for(City city : country.getCities()){ // do some operations } ``` Using country.getCities() is costly? Will JVM maintain the stacktrace for every call..? ``` List<City> cityList = country.getCities(); for(City city : cityList){ // do some operations } ``` What is the best way to use?

Original source