Nik Nik - 1 year ago 73
Java Question

Java - Endless loop with ListIterator .hasNext()

ArrayList<String> list = new ArrayList<String>();
list.add("test");

while(list.listIterator().hasNext()) {
System.out.println(list.listIterator().next());
}


This generates an endless loop of lines with "test". Why does this happen and how to fix it?

Answer Source

The iterator created for hasNext is not the same that is for next.

ArrayList<String> list = new ArrayList<String>();
list.add("test");
Iterator listIterator = list.listIterator()
while(listIterator.hasNext()) {
        System.out.println(listIterator.next());
}