HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Iterator Implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationiteratorstackoverflow

Problem

I had to write my own iterator implementation for my structure which has ArrayList field. An iterator is supposed to iterate over mentioned List. Any suggestions on improving it, or anything else?

public class ExamplesIterator implements Iterator {

    private List examples;  //ArrayList will be set here
    private int          index;

    public ExamplesIterator(List 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);
    }
}

Solution

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 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 you could get an Iterator by calling list.iterator();

Context

StackExchange Code Review Q#35626, answer score: 8

Revisions (0)

No revisions yet.