ChainedIterator#toString doesn't exhaust iterator itself

Implementation of toString() with side-effects is horrible
(especially for future debugging).
This commit is contained in:
Mikhail Golubev
2015-09-25 15:38:34 +03:00
parent 6d3d0a4be2
commit 3ee8506a17
3 changed files with 13 additions and 20 deletions
@@ -40,22 +40,21 @@ abstract class ChainIterationMixin<T, TPayload> {
// returns either null or a non-exhausted iterator.
@Nullable
public Iterator<T> getCurrent() {
while ((myCurrent == null || !myCurrent.hasNext()) && myLink.hasPayload()) { // fix myCurrent
while ((myCurrent == null || !myCurrent.hasNext()) && (myLink != null && myLink.myPayload != null)) { // fix myCurrent
if (myCurrent == null) {
myCurrent = toIterator(myLink.myPayload);
assert myCurrent != null;
}
else {
myLink.moveOn();
myLink= myLink.myNext;
myCurrent = null;
}
}
return myCurrent;
}
}
public boolean hasNext() {
Iterator<T> current = getCurrent();
return (current != null);
return getCurrent() != null;
}
public T next() {
@@ -43,7 +43,9 @@ public /*abstract */class ChainedListBase<TPayload> {
* @return
*/
protected ChainedListBase<TPayload> add(TPayload another) {
if (myPayload == null) myPayload = another;
if (myPayload == null) {
myPayload = another;
}
else {
ChainedListBase<TPayload> farthest = this;
while (farthest.myNext != null) farthest = farthest.myNext;
@@ -51,17 +53,4 @@ public /*abstract */class ChainedListBase<TPayload> {
}
return this;
}
// become to our next
public void moveOn() {
if (myNext != null) {
myPayload = myNext.myPayload;
myNext = myNext.myNext;
}
else myPayload = null; // position 'after the end'
}
public boolean hasPayload() {
return myPayload != null;
}
}
@@ -190,5 +190,10 @@ public class IteratorsTest extends TestCase {
assertEquals(all.size(), count);
}
public void testToStringDoesntExhaustIterator() {
final ChainIterable<String> initial = new ChainIterable<String>();
initial.addItem("foo");
assertEquals("foo", initial.toString());;
assertEquals("foo", initial.toString());
}
}