Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using for-each loop in java

Tags:

java

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?

like image 818
Vinay Veluri Avatar asked Dec 13 '12 10:12

Vinay Veluri


3 Answers

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.

like image 178
Jon Skeet Avatar answered Oct 19 '22 01:10

Jon Skeet


In both cases the getCities() is called only once.

Default disclaimer: As always you hardly ever need to worry about performance, as the compiler is much better at it than a person.

like image 28
Thirler Avatar answered Oct 19 '22 00:10

Thirler


These are equivalent. getCities() will only be executed once. (if you stick a System.out.println() in that method you should see this).

Note that it won't call getCities() multiple times not just for reasons of performance, but also because there's no guarantee that it would return the same collection each time (it may be intuitive that it returns the same collection, but not mandated)

I would prefer your first example for conciseness.

like image 1
Brian Agnew Avatar answered Oct 18 '22 23:10

Brian Agnew