Nik Nik - 6 months ago 15
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

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