Within Java programming, an Iterator represents a type of cursor. The Java Iterator interface is utilized to sequentially access all elements within a collection of Java objects. This functionality has been available in the Java programming language since the Java 1.2 Collection framework and is located within the java.util package.
Even though Java Iterator made its debut in Java 1.2, it is not the most ancient mechanism for iterating through Collection object elements. The Enumerator predates the Iterator in Java, serving as the oldest Iterator in the language. The Java Iterator interface supersedes the enumerator iterator that was initially used to iterate over certain collections such as ArrayLists.
The Java Iterator serves as the universal cursor within Java and is compatible with all classes in the Collection framework. It facilitates actions such as reading and removing elements. In contrast to the enumeration iterator interface, the Java Iterator interface offers methods with clearer and more concise names for ease of use.
Advantages of Java Iterator
Iterator in Java became very prevalent due to its numerous advantages. The advantages of Java Iterator are given as follows -
- The user can apply these iterators to any of the classes of the Collection framework.
- In Java Iterator, we can use both of the read and remove operations.
- If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they use the Java Iterator, they can simply update the Collection.
- The Java Iterator is considered the Universal Cursor for the Collection API.
- The method names in the Java Iterator are very easy and are very simple to use.
Disadvantages of Java Iterator
Despite the numerous advantages, the Java Iterator has various disadvantages also. The disadvantages of the Java Iterator are given below -
- The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a uni-directional Iterator.
- The replacement and extension of a new component are not approved by the Java Iterator.
- In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE.
- In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel pattern which implies that Java Iterator supports only Sequential iteration.
- In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the bulk volume of data.
How to use Java Iterator?
In order to utilize the Java Iterator, a user must create an instance of the Iterator interface from the collection of objects they wish to iterate over. Subsequently, this acquired Iterator keeps track of the elements in the original collection to ensure that the user can iterate through each element within the collection of objects.
When a user makes changes to the underlying collection while iterating over an Iterator associated with that collection, the Iterator usually detects this and will raise an exception the next time the user tries to access the next element through the Iterator.
Java Iterator Methods
The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total of four methods that are:
- hasNext
- next
- remove
- forEachRemaining
The forEachRemaining method was added in the Java 8. Let's discuss each method in detail.
- boolean hasNext : The method does not accept any parameter. It returns true if there are more elements left in the iteration. If there are no more elements left, then it will return false. If there are no more elements left in the iteration, then there is no need to call the next method. In simple words, we can say that the method is used to determine whether the next method is to be called or not.
- E next: It is similar to hasNext method. It also does not accept any parameter. It returns E, i.e., the next element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it throws the NoSuchElementException.
- default void remove: This method also does not require any parameters. There is no return type of this method. The main function of this method is to remove the last element returned by the iterator traversing through the underlying collection. The remove method can be requested hardly once per the next method call. If the iterator does not support the remove operation, then it throws the UnSupportedOperationException. It also throws the IllegalStateException if the next method is not yet called.
- default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no return type of the method. This method performs the particularized operation on all of the left components of the collection until all the components are consumed or the action throws an exception. Exceptions thrown by action are delivered to the caller. If the action is null, then it throws a NullPointerException.
Example of Java Iterator
Let's proceed with running a Java program to demonstrate the benefits of the Java Iterator interface. In the following code, we create an ArrayList containing names of cities. Subsequently, we create an iterator using the iterator method of the ArrayList. Finally, we iterate through the list to display each element.
Example
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)
{
ArrayList<String> cityNames = new ArrayList<String>();
cityNames.add("Delhi");
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh");
cityNames.add("Noida");
// Iterator to iterate the cityNames
Iterator iterator = cityNames.iterator();
System.out.println("CityNames elements : ");
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
System.out.println();
}
}
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida
Points to Remember
- The Java Iterator is an interface added in the Java Programming language in the Java 1.2 Collection framework. It belongs to java.util package.
- It is one of the Java Cursors that are practiced to traverse the objects of the collection framework.
- The Java Iterator is used to iterate the components of the collection object one by one.
- The Java Iterator is also known as the Universal cursor of Java as it is appropriate for all the classes of the Collection framework.
- The Java Iterator also supports the operations like READ and REMOVE.
- The methods names of the Iterator class are very simple and easy to use compared to the method names of Enumeration Iterator.