In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a collection of objects.
- It is used to traverse a collection object elements one by one.
- It is available since Java 1.2 Collection Framework.
- It is applicable for all Collection classes. So it is also known as Universal Java Cursor.
- It supports both READ and REMOVE Operations.
- Compare to Enumeration interface, Iterator method names are simple and easy to use.
Java Iterator Methods
In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples in the coming section.
- boolean hasNext():Returns true if the iteration has more elements.
- E next(): Returns the next element in the iteration.
- default void remove(): Removes from the underlying collection the last element returned by this iterator.
- default void forEachRemaining(Consumer action): Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
Advantages of Java Iterator
Compare to Enumeration interface, Java Iterator has the following advantages or benefits.
- We can use it for any Collection class.
- It supports both READ and REMOVE operations.
- It is an Universal Cursor for Collection API.
- Method names are simple and easy to use them.
Limitations of Java Iterator
However, Java Iterator has the following limitations or drawbacks.
- In CRUD Operations, it does NOT support CREATE and UPDATE operations.
- It supports only Forward direction iteration that is Uni-Directional Iterator.
- Compare to Spliterator, it does NOT support iterating elements parallel that means it supports only Sequential iteration.
- Compare to Spliterator, it does NOT support better performance to iterate large volume of data.
To overcome these limitations, Java has introduced two more Cursors: ListIterator and Spliterator. We will discuss about these two cursors in my coming posts.
Comments
Post a Comment