Monday, 16 April 2012

Iterator Vs ListIterator

Basically there are two differences 


1) Iterator is used to traverse the Set, List and Map where as ListIterator is used for only List type Objects


2) By Using Iterator we can We can traverse the Objects in One Direction (i,e Forward direction only using next() Metod) , By Using ListIterator we can traverse the Objects in BiDirectional i,e (forward as well as backward) by using  prnext() andevious() Methods


and 


Iterator is Base class for ListIterator i,e ListIterator extends Iterator 

Metods in Iterator and ListIterator


  1.     ListIterator Methods 

  2.    1) hasNext()

  3.    2) next()

  4.   3) remove()

  5.    4) hasPrevious()
  6.    
  7.    5) previous()

  8.    6) nextIndex()
            Iterator Methods
  1. next()

  2. hasNext()

  3. remove()



and One More Important thing is
by using the ListIterator we can modify the list when run time i,e When we are traversing the List


http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ListIterator.html

Example:

ArrayList<String> arl = new ArrayList<String>;
arl.add("1");
arl.add("2");
arl.add("3");
arl.add("4");
arl.add("5");


//Iterating the list using ListIterator
//forward direction


ListIterator itr = arl.listIterator();


while(itr.hasNext())
   System.out.println(itr.next());


//reverse direction



while(itr.hasPrevious())
   System.out.println(itr.previous());








No comments:

Post a Comment