What is the difference between these two for loop syntax, and when is each used:
for (String word : words) {
}
for (int i = 0; i < words.size(); i++) {
}
word is a string variable and words is an array.
if you need index variable "i" use normal for loop, otherwise use foreach loop, that is
for (String word : words).
The former is called "Enhanced" for loop and works on arrays and also any class implementing the java.lang.Iterable interface. So not just collections. :^)
The latter is usually used when you need to know the iteration count.
Practically there is a difference: you don't have the index of the current element.
Technically there is a larger difference. The foreach loop only works on Iterable
objects. In Java all collections (List, Vector, Map, Set) and arrays are iterable for example. These are basically classes that implement Iterable
. This for-each loop:
for (String word : words)
{
}
gets compiled to something like this:
for (Iterator<String> it = words.iterator(); it.hasNext(); )
{
String word = it.next();
}
The Iterable
interface requires the Iterator<T> iterator()
method.
Another difference is that using the for-each approach, the underlying iterators prevent you from modifying the collection over which you are iterating. Why? Because, what would happen if you are in a foreach loop and you insert or delete an element? That would make no sense and is therefor forbidden. You will get a ConcurrentModificationException
if you try to do so. You can do this with a classic loop, but you should be careful when you do that.
The first one you wrote is a foreach loop. It is a special for loop, where you conveniently loop through all instances from an array or a collection. That way you don't need another variable to save the index, but to use it, you must have an array or collection of elements.
The second one is a basic for loop, which gives you more options - you can use it not only for looping through collections, but also if you want to repeat a procedure several times. So you don't need an array or collection.
The way you used these loops in your examples, it makes no difference other than that the first example is easier to read.
The for-each loop gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely.
for (String word : words) {
}
The loop above reads as “for each word word in words.”
There is no performance penalty for using the traditionnal for-each
loop.
probably it depends on the language, but I assume there is no difference.
The syntax of the first example is easier but there is no counter so you should probably also declare another variable. In the second case you have it already..
The two loops you coded are not quite equivalent. These two are closer:
for (String word : words) {
}
for (int i = 0; i < words.size(); i++) {
String word = words[i];
}
Notice the declaration of the String variable and assignment to it.
The first loop, known as a foreach loop, declares, assigns and iterates and the exact same syntax can be used to iterate over collections (ie Iterable objects).
The only downside is you don't have access to the index. If you don't need it, use the foreach.
I don't know which language you are using , but I assume Java so for the first loop is called a for each loop I I usually use it when there is iteration or even list
List<String> myList = new ArrayList<String>();
however here is more well written answer
This loop can be used very well with iteration over arrays and other such collections. Though you can use a “for” loop with the iteration operator, the code becomes much more readable with for-each loop when dealing with huge numbers. This loop is preferred to the “for” loop, not always, but when the following conditions are seen:
- Assigning elements: Avoid using for-each loop when you need to assign a value to an element. This loop can be used when only access is desired.
- Use with single structure: You cannot use the loop when you need to compare two arrays in a situation.
- Forward iterations only: Use the “for-each” loop only for forward looping and that too in single steps.
- Compatibility: If you need your code to be compatible with versions before Java 5, you might want to go for the regular for loop.
as for the 'for loop' it can be used when specific task need to be repeat number of times
for example here if words.size() is 10 the the loop will repeat 9 (because there is no equal only < ) times
for (int i = 0; i < words.size(); i++) {
System.out.println("My output");
}
source : https://www.udemy.com/blog/for-each-loop-java/ here is similar question which was asked before When to use the for loop over the while loop?
The first notation creates an object of the specified class for each element of the collection. Second notation is usefull with primitive arrays. However, Java 8 introduces a new notation to iterating trough a collection.
myIterable.forEach(element -> doSomething...);