ArrayList iterator does not work when declaring in a loop

Why does the first snip work in an infinite loop while the second works?

//Initial code
ArrayList<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
while(myList.iterator().hasNext()) {
    System.out.println(myList.iterator().next());
}
System.out.println();



//Correct code
ArrayList<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
Iterator itr = myList.iterator();
while(itr.hasNext()) {
    System.out.println(itr.next());
}
System.out.println();
+4
source share
2 answers

In the first version of the code, a new instance is created in each iteration of the loop Iteratorbecause the method is called ArrayList#iterator(). The call iterator()will return a new instance Iteratoreach time. I suspect you think it iterator()works similarly to Java beans getXXXX, but it doesn’t.

//new Iterator Instance will always have a next item
//Iterator is a different instance during each iteration
while(myList.iterator().hasNext()) { 
    System.out.println(myList.iterator().next());
}
System.out.println();

Iterator , hasNext() Iterator. .next(), , , , , hasNext false.

//Same instance of the iterator for each iteration
Iterator itr = myList.iterator();
while(itr.hasNext()) {
    System.out.println(itr.next());
}

Iterator itr = myList.iterator();
Iterator itr2 = myList.iterator();
System.out.println(itr == itr2 ? "Same":"Different"); //outputs Different

ArrayList#iterator:

 //notice how a new instance of the Nested Itr class is created
 public Iterator<E> iterator() {
     return new Itr(); 
 }
+8

, iterator(), Iterator . , Iterator. .

+11

Source: https://habr.com/ru/post/1544541/


All Articles