[edit] Java Iterators
Iterator is of great help when we want any operation to be executed in Cycles, so Iterator will be the best choice if we want the elements of a collection to cycle and display each element. Listiterator extends Iterator.
The following steps are recommended to be followed if we want to implement Iterator :
1. Call the collection’s Iterator ( ) method to get to the strat of the Iterator.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
We can also implement ListIterator for the collections that element that implement List interface and it works more or less like Iterator.
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class IteratorExample {
public static void main(String args[]) {
Set set = new LinkedHashSet();
set.add("1");
set.add("2");
set.add("3");
set.add("4");
Iterator iter = set.iterator();
for(;iter.hasNext();) {
String element = (String) iter.next();
System.out.println(element);
}
}
}
|