Thursday, 30 April 2015

Difference between Iterator and List Iterator Example

/*
 *    Iterator traverse elements only in one direction i.e forward
 *    ListIterator traverse elements in both directions i.e forward and backward
 *    Using ListIterator we can modify the existing list as well as done in below sample
 */

public class IteratorClass extends Activity
{

ArrayList<String> miteratorList;
Iterator<String> mIterator;
ListIterator<String> mListIterator;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initiViews();
}

private void initiViews()
{
//Initializing the ArrayList
miteratorList=new ArrayList<String>();

//Adding values to the ArrayList
miteratorList.add("A");
miteratorList.add("B");
miteratorList.add("C");
miteratorList.add("D");
miteratorList.add("E");


//method to traverse elements using Iterator here
usingIterator();

//Initializing the mListIterator here
mListIterator=miteratorList.listIterator();

//method to traverse and modify elements using mListIterator here
usingListIterator();

//method to traverse elements using Iterator here
usingIterator();

usingListIteratorTOTraverseBackward();

}


private void usingIterator()
{
//Initializing the mIterator here
mIterator=miteratorList.iterator();//Returns an iterator on the elements of this list.
while(mIterator.hasNext())
{
Object element = mIterator.next();
System.out.print(element + " ");
}

//O/P goes like this => 04-29 18:32:44.590: I/System.out(26302): A B C D E

System.out.println();
}


private void usingListIterator()
{
//Modifying the existing list using list iterator
while (mListIterator.hasNext()) {
Object element=mListIterator.next();
mListIterator.set(element+"Z");  
}

System.out.println();

//04-29 18:45:44.588: I/System.out(1605): AZ BZ CZ DZ EZ

}


private void usingListIteratorTOTraverseBackward()
{
// Now, display the list in reverse order using ListIterator
     while(mListIterator.hasPrevious()) {
        Object element = mListIterator.previous();
        System.out.print(element + " ");
      }
      System.out.println();
     
          // 04-29 18:52:30.478: I/System.out(5954): EZ DZ CZ BZ AZ

}

}

No comments:

Post a Comment