title: iterator vs for loop and why iterator was introduced as we had for loop?
body: <blockquote>
    <p><strong>Possible Duplicates:</strong><br>
    <a href="https://stackoverflow.com/questions/3328672/what-are-the-advantages-of-enhanced-for-loop-and-iterator-in-java">What are the Advantages of Enhanced for loop and Iterator in Java ?</a><br>
    <a href="https://stackoverflow.com/questions/256859/is-there-a-performance-difference-between-a-for-loop-and-a-for-each-loop">Is there a performance difference between a for loop and a for-each loop?</a>  </p>
  </blockquote>
  
  
  
  <p>Below code shows that with both for loop as well as with iterator we can iterate the elements of collection then what is the difference between for loop and iterator and why we should use only iterator in case of collection</p>
  
  <pre><code>    ArrayList&lt;String&gt; list=new ArrayList&lt;String&gt;();
      list.add("dipu");
      list.add("alok");
      list.add("alok");
      list.add("jyoti");
      ArrayList&lt;Integer&gt; al=new ArrayList&lt;Integer&gt;();
      al.add(1);
      al.add(2);
      String a[]={"a","b"};
      for(int i=0;i&lt;list.size();i++)
      {
          System.out.println(list.get(i));;
      }
      for(Integer t:al)
      {
          System.out.println(t);
      }
      for (Iterator iter = list.iterator(); iter.hasNext();)
          {
          System.out.println(iter.next());
          }
      Iterator it=list.iterator();
      while(it.hasNext())
      {
      String st=it.next().toString();
      System.out.println(st);
      }
  </code></pre>