Difference between foreach loop and an Iterator


package com.manish;

import java.util.*;

public class Test1

{

    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");     //  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");      //   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 theforward direction only.If you want to access the elements in both forwardand reverse direction then you can use listIterator interface ( subclass of Iterator interface ).

No comments:

Post a Comment