Need of Iterator class in Java?
<p>The question might be pretty vague I know. But the reason I ask this is because the class must have been made with some thought in mind.</p>

<p>This question came into my mind while browsing through a few questions here on SO.</p>

<p>Consider the following code:</p>

<pre><code>class A
{

    private int myVar;

    A(int varAsArg)
    {
          myVar = varAsArg;
    }

   public static void main(String args[])
   {

      List&lt;A&gt; myList = new LinkedList&lt;A&gt;();
      myList.add(new A(1));
      myList.add(new A(2));
      myList.add(new A(3));

      //I can iterate manually like this:
      for(A obj : myList)
                 System.out.println(obj.myVar);

      //Or I can use an Iterator as well:
      for(Iterator&lt;A&gt; i = myList.iterator(); i.hasNext();)
      {
         A obj = i.next();
         System.out.println(obj.myVar);
      }
   }
}
</code></pre>

<p>So as you can see from the above code, I have a substitute for iterating using a <code>for</code> loop, whereas, I could do the same using the <code>Iterator</code> class' <code>hasNext()</code> and <code>next()</code> method. Similarly there can be an example for the <code>remove()</code> method. And the experienced users had commented on the other answers to use the <code>Iterator</code> class instead of using the <code>for</code> loop to iterate through the <code>List</code>. Why?</p>

<p>What confuses me even more is that the <code>Iterator</code> class has only <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Iterator.html" rel="nofollow">three</a> methods. And the functionality of those can be achieved with writing a little different code as well.</p>

<p>Some people might argue that the functionality of many classes can be achieved by writing one's own code instead of using the <code>class</code> made for the purpose. Yes,true. But as I said, <code>Iterator</code> class has only three methods. So why go through the hassle of creating an extra class when the same job can be done with a simple block of code which is not way too complicated to understand either.</p>

<hr>

<p>EDIT:</p>

<p>While I'm at it, since many of the answers say that I can't achieve the remove functionality without using <code>Iterator</code>,I would just like to know if the following is wrong, or will it have some undesirable result.</p>

<pre><code>for(A obj : myList)
{
           if(obj.myVar == 1)
                 myList.remove(obj);
}
</code></pre>

<p>Doesn't the above code snippet do the same thing as <code>remove()</code> ?</p>
