Iterator vs Foreach in Java
In the given tutorial, Iterator verses for each loop is explained neatly.
Iterator :
- Iterator belongs to java.util package, which is an interface and also a cursor.
- Cursors are used to retrieve elements from Collection type of object in Java.
- Iterator is recognized as Universal Java Cursor because supports all types of Collection classes.
- It is unidirectional (forward direction).
- Supporting methods of Iterator are : ref.iterator(), ref.hasNext() and ref.next().
- hasNext() method checks whether the elements are present inside a Collection object or not. Its return type is boolean.
For each loop :
- For each loop is also used for iteration of elements.
- For each loop brings different type of way for iteration of elements from Collection type of object or from an array.
- For each loop achieves iteration of the elements by executing every element one at a time sequentially.
- It is recommended because it makes code readable.
Difference between Iterator & for each loop :
- While utilizing for each loop, size check is not necessary. But while utilizing iterator, hasNext() has to be used correctly or NoSuchElementException occurs.
- While utilizing for each loop ConcurrentModificationException can occur, if the given object gets changed or altered. But while utilizing iterator, that will be not a issue.
- In Performance criteria, both Iterator and for each are same .
Program :
Lets see a program where we will use both Iterator & for each loop in a collection.
package java; import java.util; public class Traversal { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<>(); al.add(11); al.add(22); al.add(33); al.add(44); al.add(55); System.out.println("Given Arraylist usling for each loop: "); //Applying for each loop here for(int i: al) { System.out.print(i+" "); } //utilizing iterator in here Iterator<Integer> it = al.iterator(); System.out.println("\nGiven Arraylist using iterator: "); while(it.hasNext()) { System.out.print(it.next()+" "); } } }
Output :
When we will execute the class Traversal, Output is going to be :
Given Arraylist using for each loop: 11 22 33 44 55 Given Arraylist using iterator: 11 22 33 44 55
Iterator and for each loop are preferable rather than making use of for loop for traversing the elements without random access.
Leave a Reply