I had to write my own iterator implementation for my structure which has ArrayList<Vector>
field. An iterator is supposed to iterate over mentioned List
. Any suggestions on improving it, or anything else?
public class ExamplesIterator implements Iterator<Vector> {
private List<Vector> examples; //ArrayList<Vector> will be set here
private int index;
public ExamplesIterator(List<Vector> examples) {
this.examples = examples;
index = 0;
}
@Override
public Vector next() {
if(hasNext()) {
return examples.get(index++);
} else {
throw new NoSuchElementException("There are no elements size = " + examples.size());
}
}
@Override
public boolean hasNext() {
return !(examples.size() == index);
}
@Override
public void remove() {
if(index <= 0) {
throw new IllegalStateException("You can't delete element before first next() method call");
}
examples.remove(--index);
}
}
remove()
twice in a row, or without callingnext()
first. See this code I have written here for some ideas: github.com/hunterhacker/jdom/blob/master/core/src/java/org/… \$\endgroup\$