Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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);
    }
}
share|improve this question
2  
In Java it is illegal to call remove() twice in a row, or without calling next() first. See this code I have written here for some ideas: github.com/hunterhacker/jdom/blob/master/core/src/java/org/… –  rolfl Nov 18 '13 at 19:32
    
@rolfl I will take this into account. Thanks. :) –  ashur Nov 19 '13 at 20:15
add comment

1 Answer 1

up vote 5 down vote accepted

I think your implementation is overall very good, two small comments:

  • Improving readability for return statement in hasNext to return examples.size() != index;
  • Making the examples field final: private final List<Vector> examples;

However, if the Vector class here is java.util.Vector you should know that it is considered deprecated in favor of the ArrayList class.

Also, since you create your iterator from a List<Vector> you could get an Iterator<Vector> by calling list.iterator();

share|improve this answer
    
Well... I completely forgot about that I can call list.iterator(); :P. Thank you ! –  ashur Nov 19 '13 at 20:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.