Iterator interface in java and its use.
Iterator interface in java is a part of collection framework in java.util package.It is used to iterate through a collection Ex : HashMap , HashSet etc.
There are three types iterators :
- Enumeration ~
this interface is for legacy collection(Vector, Hashtable) .it goes only in forward direction.
//e is an object of Enumeration type interface
//vec is a vector class objectEnumeration e = vec.elements();
- iterator ~
this is an universal iterator which can be used for any collection object.It is only forward directional.
//instantiating iterator objectIterator itrerator_object = collection_object.iterator()
it has followinf functions:
// Returns true if the iteration(vales in a collection) has more elements
// public boolean hasNext();
//public Object next();
//public void remove();while(iterator_object.hasNext())
{
int x = iterator_object.next();
System.out.println(x);//removing the next element from the iterationiterator_object.remove();}
- ListIterator ~
this only applicable for list collection and is bidirectional.
// ListIterator_object is of type ListIterator interfaceListIterator ListIterator_object = list_object.listIterator();
it has more functions than iterator:
// Forward direction
//public boolean hasNext();
//public Object next();
//public int nextIndex();
// Backward direction
//public boolean hasPrevious();
//public Object previous();
//public int previousIndex();
// Other Methods
//public void remove();
// Replaces at current position
public void set(Object obj);
// Inserts at current position
public void add(Object obj);