diff --git a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java index 023648de1..e17254367 100644 --- a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java +++ b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java @@ -18,6 +18,7 @@ package org.apache.commons.math.linear; import java.util.Iterator; +import java.util.NoSuchElementException; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.MathRuntimeException; @@ -875,34 +876,23 @@ public abstract class AbstractRealVector implements RealVector { /** Dimension of the vector. */ private final int dim; - /** Temporary entry (reused on each call to {@link #next()}. */ - private EntryImpl tmp = new EntryImpl(); - - /** Current entry. */ + /** last entry returned by {@link #next()} */ private EntryImpl current; - /** Next entry. */ + /** Next entry for {@link #next()} to return. */ private EntryImpl next; /** Simple constructor. */ protected SparseEntryIterator() { dim = getDimension(); current = new EntryImpl(); - if (current.getValue() == 0) { - advance(current); - } - if(current.getIndex() >= 0){ - // There is at least one non-zero entry - next = new EntryImpl(); - next.setIndex(current.getIndex()); - advance(next); - } else { - // The vector consists of only zero entries, so deny having a next - current = null; + next = new EntryImpl(); + if(next.getValue() == 0){ + advance(next); } } - /** Advance an entry up to the next non null one. + /** Advance an entry up to the next nonzero one. * @param e entry to advance */ protected void advance(EntryImpl e) { @@ -919,22 +909,18 @@ public abstract class AbstractRealVector implements RealVector { /** {@inheritDoc} */ public boolean hasNext() { - return current != null; + return next.getIndex() >= 0; } /** {@inheritDoc} */ public Entry next() { - tmp.setIndex(current.getIndex()); - if (next != null) { - current.setIndex(next.getIndex()); - advance(next); - if (next.getIndex() < 0) { - next = null; - } - } else { - current = null; - } - return tmp; + int index = next.getIndex(); + if(index < 0){ + throw new NoSuchElementException(); + } + current.setIndex(index); + advance(next); + return current; } /** {@inheritDoc} */ diff --git a/src/site/xdoc/changes.xml b/src/site/xdoc/changes.xml index 1ded6c7d2..ad616b3e3 100644 --- a/src/site/xdoc/changes.xml +++ b/src/site/xdoc/changes.xml @@ -58,6 +58,9 @@ The type attribute can be add,update,fix,remove. Fix spelling of getSparcity [sic] method of OpenMapRealVector + + Fix problem with the default sparseIterator when a RealVector has exactly one non-zero entry +