Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Nik Avatar asked May 18 '16 11:05

Nik


1 Answers

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());
}
like image 182
inigo skimmer Avatar answered Oct 03 '22 08:10

inigo skimmer