a for loop is a construct that says "perform this operation n. times".
a foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"
c# - What is the difference between for and foreach? - Stack Overflow
Can someone explain foreach loops?
foreach - In detail, how does the 'for each' loop work in Java? - Stack Overflow
Iโm struggling to understand For Each Loop, can anyone explain it in simple terms with example?
Videos
a for loop is a construct that says "perform this operation n. times".
a foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"
You can use foreach if the object you want to iterate over implements the IEnumerable interface. You need to use for if you can access the object only by index.
I did multiple google searches but my brain just can't comprehend foreach loops so can someone explain them in a simple definition?
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.
If the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification.
for (int i = 0; i < someArray.length; i++) {
String item = someArray[i];
System.out.println(item);
}
The construct for each is also valid for arrays. e.g.
String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };
for (String fruit : fruits) {
// fruit is an element of the `fruits` array.
}
which is essentially equivalent of
for (int i = 0; i < fruits.length; i++) {
String fruit = fruits[i];
// fruit is an element of the `fruits` array.
}
So, overall summary:
[nsayer] The following is the longer form of what is happening:
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) { String item = i.next(); System.out.println(item); }Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for( : ) idiom, since the actual Iterator is merely inferred.
[Denis Bueno]
It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.