使用 Iterator 遍歷時,若在循環體內多次調用 it.next(),會導致**游標重複前移**,造成元素跳過,甚至拋出 NoSuchElementException。
while (it.hasNext()) {
// 錯誤:調用了兩次 next(),游標移動兩次
System.out.println(((Person) it.next()).getName() + "--" + ((Person) it.next()).getAge());
// 若集合元素為奇數,第二次 next() 會拋出異常
}
while (it.hasNext()) {
Person p = (Person) it.next(); // 只調用一次,保存引用
System.out.println(p.getName() + "--" + p.getAge());
}
Iterator 內部維護一個 cursor 游標,初始為 0。next() 返回 elementData[cursor++],**每次調用都會使游標 +1**。hasNext() 判斷 cursor != size。因此,循環體內**必須且只能調用一次 next()**,否則邏輯與游標狀態不一致。


for (Person p : list)),編譯器自動生成正確 Iterator 代碼,杜絕手寫錯誤。ListIterator 或普通 for (int i=0; i。 list.forEach(p -> ...) 同樣安全且簡潔。