Monday, 23 March 2015

Difference between for each loop and an Iterator

package com.manish;
import java.util.*;
public class Test

{

    public static void main(String[] args)

    {

         List lst=new ArrayList();

         lst.add("Manish"); 

         lst.add("Nitesh");

        lst.add("Rupesh"); 

         lst.add("Shubham");

         lst.add("prerit");

// Using for  each we don't have a chance to remove object from the list.

        for(Object l:lst)

        {

            //    lst.remove("Rupesh");     /*    Not OK

 java.util.ConcurrentModificationException   */

        }

        System.out.println(lst);     

 //   O/P    [Manish, Nitesh, Rupesh, Shubham, prerit]

    

// Using iterator we have  a chance to remove  object from the list while iterating  using iterator object.

        Iterator it=lst.iterator();

        while(it.hasNext())

        {

            Object obj=it.next();

            if(obj.equals("Rupesh"))

            {

                 lst.remove("Rupesh");  /*  Not OK it will throw

      java.util.ConcurrentModificationException */

                it.remove();    // OK

            }   

        }

        System.out.println(lst);     

 //  O/P  [Manish, Nitesh, Shubham, prerit]

    }

}

Note: In addition,in the case of for each loop we can access the elements in the forward direction only.If you want to access the elements in both forward and reverse direction then you can use listIterator interface (subclass of Iterator interface).

No comments:

Post a Comment