Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are for-each expressions in Java translated to? [duplicate]

Tags:

java

foreach

 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?

like image 318
Roay Spol Avatar asked Apr 29 '13 09:04

Roay Spol


People also ask

What is a for-each loop java?

Java 5 introduced an for-each loop, which is called a enhanced for each loop. It is used to iterate over elements of an array and the collection. for-each loop is a shortcut version of for-loop which skips the need to get the iterator and loop over iterator using it's hasNext() and next() method.

Why for-each loop is used?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.


2 Answers

Its equivalent to

for(Iterator<SomeListElement> i = objectWithList.getList().iterator();                                                                i.hasNext(); ) {   SomeListElement element = i.next();   //access element here } 
like image 177
Suresh Atta Avatar answered Oct 02 '22 06:10

Suresh Atta


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(); } 
like image 41
sanbhat Avatar answered Oct 02 '22 05:10

sanbhat