Java
Collection
Framework
: Iterator
Java Collection Framework:
Iterator
• Iterator is universal Iterator, we can apply iterator on
any collection Object.
• Iterator is the only cursor available for entire collection framework.
• Iterator object can be created by calling iterator() method present in
Collection interface.
// Here "c" is any Collection object
// type Iterator interface and refers to "c"
Iterator itr = c.iterator();
Methods in Iterator:
• Iterator interface defines three methods:
// Returns true if the iteration has more elements
public boolean hasNext();
// Returns the next element in the iteration
public Object next();
// Remove the next element in the iteration
public void remove();
Limitation of Iterator:
• Only forward direction iterating is possible.
• Replacement and addition of new element is
not supported by Iterator.
List Iterator:
• List Iterator applicable for List collection implemented classes like
arraylist, linkedlist etc. It provides bi-directional iteration.
• This cursor has more functionality(methods) than iterator.
• ListIterator object can be created by calling listIterator() method
present in List interface.
// Here "l" is any List object, ltr is of type
// ListIterator interface and refers to "l"
ListIterator ltr = l.listIterator();
List Iterator Methods:
• ListIterator interface extends Iterator interface. So all three
methods of Iterator interface are available for ListIterator. In addition
there are six more methods.
1. public boolean hasNext() - Returns true if the iteration has more
elements
2. public Object next() - same as next() method of Iterator
List Iterator Methods:
3. public int nextIndex() - Returns the next element index
4. public boolean hasPrevious() - Returns true if the iteration has more
elements
5. public Object previous() - Returns the previous element in the iteration
6. public int previousIndex() - Returns the previous element index
7. public void remove() - same as remove() method of Iterator
8. public void set(Object obj) - Replaces the last element returned by
next() or previous() with the specified element