Monday, 7 May 2018

Difference between for each loop and iterator?

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




package collectctiondemo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
           
            public static void main(String[] args) {
                        List<String> l=new ArrayList<>();
                        l.add("govind");
                        l.add("ballabh");
                        l.add("khan");
                        l.add("java");
                         l.add("technology");
                System.out.println("------------List Data----------");
                System.out.println(l);
             // Using for  each we don't have a chance to remove object from the list.
                System.out.println("-------------Using For each loop----------");
                for(String s1:l)
                {
                        System.out.println(s1); 
                        //l.remove("ballabh");//java.util.ConcurrentModificationException
                }
               
                System.out.println("-------------Using iterator ----------");
             // Using iterator we have  a chance to remove  object from the list while iterating  using iterator object.
               
               Iterator<String> it = l.iterator();
               while (it.hasNext()) {
                        String s1 =  it.next();
                        System.out.println(s1);
                        //l.remove(s1);//java.util.ConcurrentModificationException
                        if(s1.equals("ballabh"))
                                    it.remove();
            }
               System.out.println("----------------After remove operation------------");
               System.out.println(l);
               
               
             
                       
            }

}


o/p:----------------------------------


------------List Data----------

[govind, ballabh, khan, java, technology]
-------------Using For each loop----------
govind
ballabh
khan
java
technology
-------------Using iterator ----------
govind
ballabh
khan
java
technology
----------------After remove operation------------
[govind, khan, java, technology]

No comments:

Post a Comment