Difference between for loop and Enhanced for loop in Java? Example Tutorial
Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list, set, or map. There are some key differences between them. In general, enhanced for loop is much easier to use and less error-prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control the looping process. All the differences, you will learn in this article, stems from the very fact that traditional for loop gives more control than enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience.
So, the choice is up to you, if you need more control then traditional for loop is ideal and if you don’t need that level of control, just opt for convenience by using enhanced for loop as shown here.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
Difference between for loop and advanced for loop in Java
1) The for loop is present from the start i.e. JDK 1, but enhanced for loop was added on Java 5, hence it’s only available from JDK 5 onward.
2) In order to loop over a container using enhanced for loop, your container must implement the Iterable interface, both array and collection implement this, but there is no such requirement for traditional for loop.
2) The enhanced for loop executes in sequence. i.e the counter is always increased by one, whereas in for loop you can change the step as per your wish e.g doing something like i=i+2; to loop every second element in an array or collection.
3) The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrement. i.e in for loop we can write i— in step counter to go backward.
4) You don’t have access to array index in enhanced for loop, which means you cannot replace the element at giving the index, but for loop provide access to the index, hence allows you to replace any element in the array.
5) If we have a requirement that the array should be displayed sequence in the forward direction and we also don’t want to change the real value in the array accidentally or intentionally by any user etc then we should use the enhanced for loop.
6) Since Java 8, you can also use the forEach() method to iterate over a collection in Java. This method is added in both the Iterable and Stream interface to allow seamless iteration using functional programming idiom.
Here is the sample program to demonstrate how you can use both for loop and enhanced for loop to iterate over an array and a list in Java.
Iterating over a list in Java
You can see that elements of a list are displayed in sequence using both traditional and enhanced for loop in Java. Now, let’s see how to iterate over an array in Java using both kinds of loops in Java:
Iterating over an array in Java
That’s all about the difference between a loop and an enhanced for loop in Java. If you only want to iterate over elements from an array or a collection e.g. a list or a set then use enhanced for loop, it’s convenient and less error-prone, but if you want more control over the iteration process then use traditional for loop.
3 comments :
Hello Himanshu, an object which holds other objects is commonly known as container. For example, Collection interface in Java or List, Set they hold other objects they are called container or collection class. In order for them to be used inside enhanced for loop, they must implement Iterable interface. This means if you write your own container, very low chance you can implement Iterable interface in order to make it usable with enhanced for loop.
The «enhanced for loop» is not less powerful by any means. It only seems so because you are restricting yourself to iterating through an array. But the «enhanced for loop» allows you to iterate through any collection. Would you like to iterate through for loop through a binary tree? An n-ary tree? A cyclic graph? A set?
for (item i : myCollection) <
/* whatever you want */
>
почему enhanced for loop более эффективен, чем обычный для цикла
Я прочитал, что улучшенный цикл for является более эффективным, чем обычный цикл здесь:
когда я искал разницу между их эффективностью, все, что я нашел: в случае нормального для цикла нам нужен дополнительный шаг, чтобы узнать длину массива или размер и т. д.,
но это единственная причина, усиленные для цикл лучше, чем нормальный для цикла? В этом случае лучше использовать обычный цикл из-за небольшой сложности в понимании усиливается цикл.
может ли кто-нибудь объяснить внутреннюю реализацию этих двух типов циклов for или объяснить другие причины использования enhanced цикл?
7 ответов
это немного упрощение, чтобы сказать, что расширенный цикл for более эффективен. Это можете быть, но во многих случаях это почти точно так же, как старая школа петлю.
одно место где увеличенное для цикл быстрее, чем наивно реализован традиционный цикл-это что-то вроде этого:
Я сам удивлен в небольшом эксперименте, который я сделал сегодня с вышеупомянутыми пунктами. Итак, я сделал то, что я вставил определенное количество элементов в связанный список и повторил его, используя вышеупомянутые три метода 1) используя advanced for loop 2) используя Iterator 3) используя simple loop и get ()
Я думаю, программисты, такие как вы, ребята, могут лучше понять, что я сделал, увидев код.
ось Y-прошедшее время X axis-тестовый случай
тест case1: 10 входов
тест case2: 30 входов
тест case3: 50 входов
тест case4: 100 входов
тест case5: 150 входов
тест case6: 300 входов
тест case7:500 входов
тест case8: 1000 входов
тест case9:2000 входов
тест case10:5000 входов
тест case11: 10000 входов
тест case12: 100000 входов
Я прочитал, что enhanced for loop эффективнее, чем обычно для цикла.
на самом деле иногда его менее эффективным для программы, но большую часть времени его точно так же.
его более эффективным для разработчика, который часто гораздо важнее
a для каждого цикла особенно полезен при итерации по коллекции.
легче писать как (но делает то же самое, что и, поэтому его не более эффективным для программы)
использование» старого » цикла немного эффективнее при доступе к случайно доступной коллекции по индексу.
использование цикла for-each в коллекции всегда использует итератор, который немного менее эффективен для списков произвольного доступа.
AFAIK, используйте цикл for-each никогда не бывает более эффективным для программы, но, как я уже сказал, эффективность разработчика часто гораздо важнее.
for-each использует интерфейс итератора. Сомневаюсь, что он эффективнее, чем «старый» стиль. Итератор также должен проверить размер списка.
Это в основном для удобства чтения.
Это должно быть быстрее для коллекций с неслучайным доступом, таких как LinkedList, но тогда сравнение несправедливо. В любом случае вы не использовали бы вторую реализацию (с медленным индексированным доступом).
цикл foreach так же эффективен, как и этот вид цикла:
потому что это строго эквивалентны.
Если вы перебираете список с помощью
тогда цикл foreach будет иметь эквивалентную производительность как ваш цикл,но только для ArrayList. В случае LinkedList ваш цикл будет иметь ужасную производительность, потому что на каждой итерации ему придется пересекать все узлы списка, пока он не доберется до i th элемент.
цикл foreach (или цикл, основанный на итераторе, который является тем же), не имеет этой проблемы, так как итератор сохраняет ссылку на текущий узел и просто переходит к следующему на каждой итерации. Это выбор bast, потому что он отлично работает со всеми типами списков. Он также выражает намерение более четко и безопаснее, потому что вы не рискуете увеличивать индекс внутри цикла или использовать неправильный индекс в случае вложенных циклов.
Из Эффективной Java:
стандартная идиома для цикла через массив не обязательно приводит к избыточные проверки. Современные реализации JVM оптимизируют их.
но Джош блох не описывает, как JVM оптимизирует их.
все ответы хороши,и я думаю, что больше не нужны ответы, но я просто хочу указать на то, что:
может использоваться расширенная инструкция for только to obtain array elements
если вашей программе необходимо изменить элементы, используйте традиционный counter-controlled for заявление.
How foreach or Enhanced for loop works in Java? Example
It’s a long time since JDK 1.5 introduced the enhanced for loop, almost 12 years ago in the year 2004, but still, many Java developers don’t know the basics of enhanced for loop, also known as for each loop in Java. The enhanced loop provides the cleanest way to loop through an array or collection in Java, as you don’t need to keep track of the counter or you don’t need to call the hasNext() method to check whether there are more elements left. The key point, which many Java developer doesn’t know about the enhanced for loop is that you can use any Object which implements the Iterable interface on for (: ) construct, you can even use enhanced for loop to loop through the array.
Since JDK 8 also introduced a forEach() function to provide looping functionality, don’t confuse when I say for each loop with that. In this article, we’ll see how enhanced for loop works and a couple of important points related to it.
Btw, Java 5 introduced several useful features along with enhanced for loop like Generics, Enum, Concurrency API, Variable arguments, Static import, covariant method overriding, etc. Nowadays, it’s expected from a Java developer to know all these features by heart.
If you feel you lack in any of these then I suggest joining these free Java Programming courses from Udemy and Educative. One of the best courses to fill your gap in Java. It also covers Java SE 8.
How enhanced for loop foreach works in Java? Example
Suppose, you want to loop over a List in Java, you can write the following code to accomplish that using the enhanced for loop:
This is equivalent to the following code because enhanced for loop is nothing but a syntactic sugar over Iterator in Java:
Of course, the enhanced for loop approach is much cleaner and readable but it is also more limited as you cannot remove elements while iterating, there is no reference to the iterator to call the remove() method, and if you call remove() method of List then you will end up with ConcurrentModificationException in Java. To avoid this dreaded error see this article.
Even though enhanced for loop internally uses an Iterator, it doesn’t expose the reference to the outside world.
here is a nice summary of why enhanced for loop was introduced in Java 5 and why you should use it, along with syntax and examples of how to use it for iterating over collection and array.
ForEach Loops in Java (Enhanced For Loop)
The basic “for” loop was enhanced in Java 5 and got a name “for each loop”.
It also called: Java for each loop, for in loop, advanced loop, enhanced loop.
It’s more readable and reduces a chance to get a bug in your loop.
You can use for each loop in Java to iterate through array, Collections(Set, List) or Map.
The enhanced loop works for each class that implements Iterable interface as well.
For Each Loop Syntax in Java
The for each syntax in Java has the following form:
Since Java 8 you can use one more for each statement for Collections and Maps:
this can be even simplified using method reference:
For each statement always can be represented as a basic for loop.
An array can be represented as:
And List (or any other Iterable object) can be represented as:
Let’s take a look at code examples.
Code Examples
I prepared frequently used code examples.
For Each Loop Array
On my opinion, in case of an array, the 1st example is preferable.
For Each Loop ArrayList
On the first look Java 8 example should look like this:
But you can use the power of the Stream API and write it in one line of code:
For Each Loop Map
For Each Loop Enum
Enum.values() is array, so behavior is the same as in the 1st example.
For Each Loop Chars in String
String.toCharArray() is array, the behavior is the same as in the 1st example.
For Each Loop File In Directory
For Each Loop FAQ
I collected frequently asked questions and will try to give you short answers.
Can I Remove Elements in For Each Loop
If we’re talking about not thread-safe collections like an ArrayList or HashSet than It’s not the best idea.
ConcurrentModificationException exception will be thrown in the most cases.
You should use an iterator instead:
Or super simple solution since Java 8:
How to Get Index in For Each Loop
It’s not possible. You should use basic for loop instead.
How to Get the Last Element in For Each Loop
The same as for get index case – you should use a simple for loop instead.
For-Each Example: Enhanced for Loop to Iterate Java Array
Updated October 7, 2021
For-Each Loop is another form of for loop used to traverse the array. for-each loop reduces the code significantly and there is no use of the index or rather the counter in the loop.
Syntax:
Let us take the example using a String array that you want to iterate over without using any counters.
Consider a String array arrData initialized as follows:
Although you might know methods like finding the size of the array and then iterating through each element of the array using the traditional for loop (counter, condition, and increment), we need to find a more optimized approach that will not use any such counter.
This is the conventional approach of the “for” loop:
You can see the use of the counter and then use it as the index for the array.
Java provides a way to use the “for” loop that will iterate through each element of the array.
Here is the code for the array that we had declared earlier-
You can see the difference between the loops. The code has reduced significantly. Also, there is no use of the index or rather the counter in the loop.
Do ensure that, the data type declared in the foreach loop must match the data type of the array/list that you are iterating.
Here we have the entire class showing the above explanation-





