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?
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.
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.
Its equivalent to
for(Iterator<SomeListElement> i = objectWithList.getList().iterator(); i.hasNext(); ) { SomeListElement element = i.next(); //access element here }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With