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?
No, this loop:
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:There’s no benefit in rewriting it as per your second snippet.
See section 14.14.2 of the JLS for more details.