41
 for ( SomeListElement element : objectWithList.getList() ) { ... }

What is the above snippet translated to?

What I am mostly interested in is if the getList() method called once, or with each iteration/element?

Roay Spol
  • 1,188
  • 1
  • 11
  • 17
  • 11
    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Iterable.html – deprecated Apr 29 '13 at 09:05
  • 3
    This is a shorthand for `Iterator` solution. – skuntsel Apr 29 '13 at 09:07
  • 16
    What research did you perform before asking this question? The language specification seems to be an obvious place to look, and it gives the answer very clearly. http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2 – Jon Skeet Apr 29 '13 at 09:22
  • Can't you try yourself by adding a side effect on getList ? – Vincent Apr 29 '13 at 13:43
  • @JonSkeet I stumbled upon on this, and a side-comment which drawn my attention: `for-each`, in the spec, in the documentations (different JDK docs) or even in many books is referred to as "syntactic sugar / enhanced for loop" for iterating over a *Iterable* collections, which makes clear sense. Even [this doc](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html) exemplifies Iterable, and the corresponding bytecodes (foreach vs. for) are super similar. I wonder is foreach really using `iterator()` behind the scenes or.. Your link says it's used for arrays as well.. meh. – Giorgi Tsiklauri Sep 21 '20 at 07:12
  • @GiorgiTsiklauri: For iterables, it uses `iterator()`. For arrays, it doesn't. The JLS is the canonical source for this: https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2 – Jon Skeet Sep 21 '20 at 08:37

2 Answers2

47

Its equivalent to

for(Iterator<SomeListElement> i = objectWithList.getList().iterator(); 
                                                              i.hasNext(); ) {
  SomeListElement element = i.next();
  //access element here
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
26

It gets translated to below code snippet, and objectWithList.getList() is called only once.

for (Iterator i = objectWithList.getList().iterator(); i.hasNext();) {
    SomeListElement e = (SomeListElement) i.next();
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
sanbhat
  • 17,522
  • 6
  • 48
  • 64