Iterators versus 'cursors' in Java
<p>In Java, most people expect that each call to <code>Iterator.next()</code> will return a distinct object.  This has led some of us to define an alternative model which we called a 'cursor'. (Note that others use the term 'cursor' to draw a different distinction.) The pattern of a cursor is:</p>

<pre><code>class SomeCursor {
    boolean hasNext();
    void next();
    type1 getItem1();
    type2 getItem2();
 }
</code></pre>

<p>In other words, it is perfectly clear that the same object evolves at each step in the iteration.</p>

<p>The problem on my hand right now is to also support situations, like web services, in which we absolutely do want distinct objects so that we can ship a collection of them around.</p>

<p>It pains me to imagine pairs of classes (a cursor and a bean) that have to be maintained in parallel, and I'm casting about for alternatives.</p>

<p>Here's one idea, and I wonder if anyone else out there has seen a better one.</p>

<ol>
<li>You make an interface consisting of the 'get' methods for an object with all the items in it.</li>
<li>You define the cursor as implementing that interface and also hasNext &amp; next.</li>
<li>You dynamically create the bean objects using one of the major dynamic code-gen libs on the fly to create a class with the obvious fields and get methods, plus set methods if needed to make something like JAX-B happy.</li>
</ol>

<p>edit: for those who are not following, I recommend a read of 
<a href="http://lucene.apache.org/java/2_4_0/api/org/apache/lucene/analysis/TokenStream.html" rel="nofollow">http://lucene.apache.org/java/2_4_0/api/org/apache/lucene/analysis/TokenStream.html</a>. Also compare with <a href="http://download.oracle.com/javase/6/docs/api/java/sql/ResultSet.html" rel="nofollow">http://download.oracle.com/javase/6/docs/api/java/sql/ResultSet.html</a>, which is an example of this 'cursor' approach.</p>

<p>Note in Lucene an API that iterates over a sequence of objects, allow the caller to specify whether to deliver the new data to a new object or the same old object each time.</p>

<p>Yes, it is possible to define an <code>Iterator&lt;T&gt;</code> that returns the same thing ever time, but we have concerns that people will use this as a gun to shoot their toes off. Thus the preference for the JDBC-ish pattern.</p>
