Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning the same object from Iterator<?>
    primarykey
    data
    text
    <p>Is it valid - i.e., within the contact, for <code>Iterator</code> to return the same (mutable) object as a prior iteration, or a new object with shared mutable state as prior object? That is, may one call to <code>next()</code> to invalidate the object returned by a prior call, as long as it is documented?</p> <p>I understand perfectly well that this isn't a good idea <em>in general</em>, and I don't make a habit of it.</p> <p>However, there are some cases where reusing the same underlying object, or new object with shared internals (thus possibly invalidating internals of an object returned earlier) has a significant and measurable in some cases. A good example would be when the object returned from the iterator points with some offset and length into a buffer array held by the containing <code>Iterable</code>, and this array may be overwritten when the subsequent object is retrieved.</p> <p>Granted this violates the principle of least astonishment, and may be client unfriendly - but I'm curious if it violates the contact of <code>Iterator</code> - as long as I document it, am I playing within the rules?</p> <p>The <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html" rel="nofollow">javadoc</a> seems to have been written with a focus on collections, where sharing state between <code>next()</code> calls is probably meaningless, but <code>Iterator</code> is a general purpose interface (you can implement without a backing collection or even without a backing <em>anything</em>).</p> <p>Basically I'm trying to implement something comparable, performance-wise, to the flyweight pattern, but to retain the niceties of Java iterators.</p> <p>Iterators following this pattern would be safe to use in the following way:</p> <pre><code>for (Foo foo : FooIterable) { if (foo.method()) { System.println("ha!"); } } </code></pre> <p>since each instance of <code>foo</code> never escapes from one iteration to the other. However, something like the following would not work in general:</p> <pre><code>List&lt;Foo&gt; allTheFoos = ...; for (Foo foo : FooIterable) { allTheFoos.add(foo); } for (Foo foo : allTheFoos) { ... } </code></pre> <p>Since the <code>foo</code>s in the first loop are stored away and thus escape their iteration. When you access them later, their state may be invalid (e.g., they may all look like the last <code>foo</code> returned from the initial iteration.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload