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.
while(myList.iterator().hasNext()) {
System.out.println(myList.iterator().next());
}
System.out.println();
Iterator , hasNext() Iterator. .next(), , , , , hasNext false.
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");
ArrayList#iterator:
public Iterator<E> iterator() {
return new Itr();
}