Iterator is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection.
// Iterating over collection 'c' using terator for (Iterator i = c.iterator(); i.hasNext(); ) System.out.println(i.next());
For eachloop is meant for traversing items in a collection.
// Iterating over collection 'c' using for-each for (Element e: c) System.out.println(e);
We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element e in elements”, here elements is the collection which stores Element type items.
Note : In Java 8 using lambda expressions we can simply replace for-each loop with
elements.forEach (e -> System.out.println(e) );
In for-each loop, we can’t modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection.
Modifying a collection simply means removing an element or changing content of an item stored in the collection. This occurs because for-each loop implicitly creates an iterator but it is not exposed to the user thus we can’t modify the items in the collections.
When to use which traversal?
- If we have to modify collection, we can use Iterator.
- While using nested for loops it is better to use for-each loop, consider the below code for better understanding.
Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList$ListItr.next(LinkedList.java:888) at Main.main(Main.java:29)
The above code throws java.util.NoSuchElementException.
In the above code we are calling the next() method again and again for itr1 (i.e., for List l). Now we are advancing the iterator without even checking if it has any more elements left in the collection(in the inner loop), thus we are advancing the iterator more than the number of elements in the collection which leads to NoSuchElementException.
for-each loops are tailor made for nested loops. Replace the iterator code with the below code.
2 2 2 3 3 3 4 4
Traversing a collection using for-each loops or iterators give the same performance. Here, by performance we mean the time complexity of both these traversals.
If you iterate using the old styled C for loop then we might increase the time complexity drastically.
// Here l is List ,it can be ArrayList /LinkedList and n is size of the List
for (i=0;i<n;i++) System.out.println(l.get(i));
Here if the list l is an ArrayList then we can access it in O(1) time since it is allocated contiguous memory blocks (just like an array) i.e random access is possible. But if the collection is LinkedList, then random access is not possible since it is not allocated contiguous memory blocks, so in order to access a element we will have to traverse the link list till you get to the required index, thus the time taken in worst case to access an element will be O(n).
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java
- Static blocks in Java
- Access specifiers for classes or interfaces in Java
- java.lang.Character class methods | Set 1
- Comparison of Inheritance in C++ and Java
- Output of Java Program | Set 1
Improved By : PratikBhardwaj