Consider:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for
loop look like without using the for each syntax?
The
foreach
loop, added in Java 5 (also called the "enhanced for loop"), is equivalent to using ajava.util.Iterator
--it's syntactic sugar for the same thing. Therefore, when reading each element, one by one and in order, aforeach
should always be chosen over an iterator, as it is more convenient and concise.foreach
Iterator
There are situations where you must use an
Iterator
directly. For example, attempting to delete an element while using aforeach
can (will?) result in aConcurrentModificationException
.foreach
vs.for
: Basic differencesThe only practical difference between
for
andforeach
is that, in the case of indexable objects, you do not have access to the index. An example when the basicfor
loop is required:Although you could manually create a separate index int-variable with
foreach
,it is not recommended, since variable-scope is not ideal, and the basic
for
loop is simply the standard and expected format for this use case.foreach
vs.for
: PerformanceWhen accessing collections, a
foreach
is significantly faster than the basicfor
loop's array access. When accessing arrays, however--at least with primitive and wrapper-arrays--access via indexes is dramatically faster.Timing the difference between iterator and index access for primitive int-arrays
Indexes are 23-40 percent faster than iterators when accessing
int
orInteger
arrays. Here is the output from the testing class at the bottom of this post, which sums the numbers in a 100-element primitive-int array (A is iterator, B is index):I also ran this for an
Integer
array, and indexes are still the clear winner, but only between 18 and 25 percent faster.For collections, iterators are faster than indexes
For a
List
ofIntegers
, however, iterators are the clear winner. Just change the int-array in the test-class to:And make the necessary changes to the test-function (
int[]
toList<Integer>
,length
tosize()
, etc.):In one test they're almost equivalent, but with collections, iterator wins.
*This post is based on two answers I wrote on Stack Overflow:
Uses and syntax for for-each loop in Java
Should I use an Iterator or a forloop to iterate?
Some more information: Which is more efficient, a for-each loop, or an iterator?
The full testing class
I created this compare-the-time-it-takes-to-do-any-two-things class after reading this question on Stack Overflow:
Here is an answer which does not assume knowledge of Java Iterators. It is less precise, but it is useful for education.
While programming we often write code that looks like the following:
The foreach syntax allows this common pattern to be written in a more natural and less syntactically noisy way.
Additionally this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface.
The concept of a foreach loop as mentioned in Wikipedia is highlighted below:
So the concept of a foreach loop describes that the loop does not use any explicit counter which means that there is no need of using indexes to traverse in the list thus it saves user from off-by-one error. To describe the general concept of this off-by-one error, let us take an example of a loop to traverse in a list using indexes.
But suppose if the list starts with index 1 then this loop is going to throw an exception as it will found no element at index 0 and this error is called an off-by-one error. So to avoid this off-by-one error the concept of a foreach loop is used. There may be other advantages too, but this is what I think is the main concept and advantage of using a foreach loop.
The construct for each is also valid for arrays. e.g.
which is essentially equivalent of
So, overall summary:
[nsayer] The following is the longer form of what is happening:
[Denis Bueno]
Also note that using the "foreach" method in the original question does have some limitations, such as not being able to remove items from the list during the iteration.
The new for-loop is easier to read and removes the need for a separate iterator, but is only really usable in read-only iteration passes.
As so many good answers said, an object must implement the
Iterable interface
if it wants to use afor-each
loop.I'll post a simple example and try to explain in a different way how a
for-each
loop works.The
for-each
loop example:Then, if we use
javap
to decompile this class, we will get this bytecode sample:As we can see from the last line of the sample, the compiler will automatically convert the use of
for-each
keyword to the use of anIterator
at compile time. That may explain why object, which doesn't implement theIterable interface
, will throw anException
when it tries to use thefor-each
loop.