title: Why does Java not allow foreach on iterators (only on iterables)?
body: <blockquote>
  <p><strong>Possible Duplicate:</strong><br />
  <a href="https://stackoverflow.com/questions/839178/why-is-javas-iterator-not-an-iterable">Why is Java's Iterator not an Iterable?</a></p>
  <p><a href="https://stackoverflow.com/questions/3883131/idiomatic-way-to-use-for-each-loop-given-an-iterator">Idiomatic way to use for-each loop given an iterator?</a></p>
  <p><a href="https://stackoverflow.com/questions/2162917/can-we-use-for-each-loop-for-iterating-the-objects-of-iterator-type">Can we use for-each loop for iterating the objects of Iterator type?</a></p>
  </blockquote>
  
  <p>The foreach loop are as far as I know syntax sugar added in Java 5. So</p>
  <pre><code>Iterable&lt;O&gt; iterable;
  for(O o : iterable) {
      // Do something
  }
  </code></pre>
  <p>will essentially produce the same bytecode as</p>
  <pre><code>Iterable&lt;O&gt; iterable;
  for(Iterator&lt;O&gt; iter = iterable.iterator(); iter.hasNext(); /* NOOP */) {
      O o = iter.next();
      // Do something
  }
  </code></pre>
  <p>However, if I do not have an iterable in the first place, but only an iterator (say, because a class offers two different iterators), I cannot use the syntax sugar foreach loop. Obviously I can still do the plain old style iteration. However, I'd actually like to do:</p>
  <pre><code>Iterator&lt;O&gt; iter;
  for(O o : iter /* Iterator&lt;O&gt;, not Iterable&lt;O&gt;! */) {
       // Do something
  }
  </code></pre>
  <p>And of course I can do a fake <code>Iterable</code>:</p>
  <pre><code>class Adapter&lt;O&gt; implements Iterable&lt;O&gt; {
      Iterator&lt;O&gt; iter;
  
      public Adapter(Iterator&lt;O&gt; iter) {
          this.iter = iter;
      }
  
      @Override
      public Iterator&lt;O&gt; iterator() {
          return iter;
      }
  }
  </code></pre>
  <p>(Which in fact is an ugly abuse of the Iterable API, as it can only be iterated once!)</p>
  <p>If it were designed around <code>Iterator</code> instead of iterable, one could do a number of interesting things:</p>
  <pre><code>for(O o : iterable.iterator()) {} // Iterate over Iterable and Collections
  
  for(O o : list.backwardsIterator()) {} // Or backwards
  
  Iterator&lt;O&gt; iter;
  for(O o : iter) {
      if (o.something()) { iter.remove(); }
      if (o.something()) { break; }
  }
  for(O : iter) { } // Do something with the remaining elements only.
  </code></pre>
  <p>Does anyone know <em>why</em> the language was designed this way? To avoid ambiguity if a class would implement both <code>Iterator</code> and <code>Iterable</code>? To avoid programmer errors that assume that &quot;for(O o : iter)&quot; will process all elements twice (and forget to get a fresh iterator)? Or is there some other reason for this?</p>
  <p>Or is there some language trick I just do not know?</p>