ListIterator it = al.listIterator();
while (it.hasNext()) {
if (al.size() == 4) {
it.add("vv");
}
// 缺少 it.next(),迭代器永不前進
}
hasNext() 始終返回 true,因為迭代器游標停留在初始位置,未調用 next() 前進。
while (it.hasNext()) {
if (al.size() == 4) {
System.out.println(al.size()); // 此時 size 已變 5
it.add("vv");
}
it.next(); // 關鍵:移動游標
}
it.add() 後 al.size() 立即增加,動態反映。Iterator it = al.listIterator() 面向接口編程,實際對象是 ListIterator,可調用 add。al.add() 會導致 ConcurrentModificationException,必須用迭代器的 add/remove。