zython zython - 7 months ago 23
Java Question

ArrayList Iterator fails to iterate

My iterator which I've written, doesnt iterate as planned. It should iterate over an ArrayList but it keep looping over the first item:

aylmao


Goal is to have a working custom iterator which will iterate a generic ArrayList

I'd very much rather ask this in the chat but no one is there atm.

Heres the trouble causing code:




@Override
public Iterator<T> iterator() {
final SimpleList<T> list = this;

return new Iterator<T>() {

int index = 0;

@Override
public boolean hasNext() {
return index < list.size() && list.get(index) != null;
}

@Override
public T next() {
T temp = list.get(index++);
index++;
return temp;
}

public void remove() {
throw new UnsupportedOperationException();
}
};

}

public static void main(String[] args) {
SimpleList<String> list = new SimpleList<String>();
list.append("aylmao");
list.append("1aylmao");
list.append("2aylmao");
list.append("3aylmao");
list.append("4aylmao");
list.append("5aylmao");
list.append("6aylmao");

while (list.iterator().hasNext()) {

System.out.println(list.iterator().next());
}
}

Answer

Calling list.iterator() creates a new iterator every time.

Iterator<String> iter = list.iterator() will solve your problem

Just re-use iter.

For example:

SimpleList<String> list = new SimpleList<String>();
    list.append("aylmao");
    list.append("1aylmao");
    list.append("2aylmao");
    list.append("3aylmao");
    list.append("4aylmao");
    list.append("5aylmao");
    list.append("6aylmao");
    Iterator<String> iter = list.iterator()
    while (iter.hasNext()) {

        System.out.println(iter.next());
    }
Comments