Here's my implementation of an iteratorover an ArrayList:
public class MyClass {
List<E> list = new ArraList<E>();
public Iterator<E> iterator() {
return new MyIterator<E>();
}
private class MyIterator<T> implements Iterator<E> {
int index;
public MyIterator() {
index = 0;
}
public E next() {
if (hasNext()){
index++;
return list.get(index + 1);
}
else
throw new NoSuchElementException();
}
public boolean hasNext() {
if ((list.get(index + 1) != null) && (index < list.size() -1)){
index++;
return true;
}
else
return false;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
However, although the logic looks alright to me, this implementation is wrong, because it does not work properly.
My question is: what am i doing wrong, and how can i change it in order for it to work properly?
UPDATE:
public E next() {
if (index == 0) {
index++;
return list.get(0);
}
else if (hasNext()) {
index++;
return list.get(index);
}
else
throw new NoSuchElementException();
}
I've managed to, somehow, make it work, but now the next method is skipping indexes of the array. How can i fix this ?
PacoteIteratorArrayOutOfBoundsExceptioni don't know why