java.util.Iterator<T>
An iterator over a
collection.
Iterator takes the
place of Enumeration in the Java collections framework.
Iterators differ from enumerations in two ways:
1. Iterators allow the
caller to remove elements from the underlying collection during the iteration
with well-defined semantics.
2. Method names have
been improved.
public interface
ListIterator<E> extends Iterator<E>
An iterator for
lists that allows the programmer to traverse the list in either direction,
modify the list during iteration, and obtain the iterator's current position in
the list.
A ListIterator has
no current element; its cursor position always lies between the element that
would be returned by a call to previous() and the element that would be
returned by a call to next().
An iterator for a
list of length n has n+1 possible cursor positions, as illustrated by the
carets (^) below:
Element(0) Element(1) Element(2) ...
Element(n-1
cursor
positions:^
^
^
^ ^
Note that the remove and set(Object) methods
are not defined in terms of the cursor position; they are defined to operate on
the last element returned by a call to next or previous().
package com.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorVsListIterator
{
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("rajesh");
list.add("sattu");
list.add("shan");
System.out.println("iterator :");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
ListIterator<String> listItr = list.listIterator();
System.out.println("List Iterator : next");
while (listItr.hasNext()) {
System.out.println(listItr.next());
listItr.add("rahul");
}
System.out.println("List Iterator : previous");
while (listItr.hasPrevious())
{
System.out.println(listItr.previous());
}
}
}
Key points about Iterator:
Ø
Iterator in Java support generics so always use Generic version of Iterator rather than using Iterator with raw type.
Ø
If you want to remove objects from Collection
than don't use for-each loop instead use Iterator's remove () method to avoid any ConcurrentModificationException.
Ø
Iterating over collection using Iterator is subject to ConcurrentModificationExc if Collection is
modified after Iteration started, but this only happens in case of fail-fast Iterators.
Ø
There are two types of Iterators in Java,
fail-fast (ArrayList, HashMap) and fail-safe (CopyOnWriteList,
ConcurrentHashMap).
Ø
List collection type also supports ListIterator which
has add() method to add elements in collection while Iterating.
Output :
ReplyDeleteiterator :
rajesh
sattu
shan
List Iterator : next
rajesh
sattu
shan
List Iterator : previous
rahul
shan
rahul
sattu
rahul
rajesh