7
\$\begingroup\$

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);
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 18, 2013 at 19:25
\$\endgroup\$
2

1 Answer 1

8
\$\begingroup\$

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();

answered Nov 18, 2013 at 19:35
\$\endgroup\$
1
  • \$\begingroup\$ Well... I completely forgot about that I can call list.iterator(); :P. Thank you ! \$\endgroup\$ Commented Nov 19, 2013 at 20:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.