如果你不能使用另一個列表,你可以通過計算你通過迭代器處理的元素數量並將其與列表的原始大小進行比較來解決你的問題:所有新元素將在該列表,因此當您達到原始大小時您可以結束循環。
LinkedList<Schedule> queue = new LinkedList<Schedule>(schedules);
int origSize = queue.size();
int currCount = 0;
ListIterator<Schedule> iterator = queue.listIterator();
while (iterator.hasNext()) {
++currCount;
if (currCount >= origSize) {
break; // reached the end of the original collection
}
Schedule schedule = iterator.next();
if(condition)
iterator.add(new Schedule());
}
你也可以使用一個額外的列表來跟蹤新的元素,並添加到原始列表後的處理結束:
LinkedList<Schedule> queue = new LinkedList<Schedule>(schedules);
LinkedList<Schedule> addQueue = new LinkedList<Schedule>();
ListIterator<Schedule> iterator = queue.listIterator();
while (iterator.hasNext()) {
Schedule schedule = iterator.next();
if(condition)
addQueue.add(new Schedule());
}
queue.addAll(addQueue);
另外,還要注意iterator.add()
將指定的元素插入列表(可選操作)。該元素緊接在下一個元素(如果有的話)和下一個元素之前(如果有)返回的下一個元素之前插入。 (如果列表不包含元素,則新元素成爲列表中的唯一元素。)新元素插入到隱式遊標之前:後續對下一個元素的調用不受影響,隨後對前一個元素的調用將返回新元素。 (這個調用由一個數值增加,將通過向nextIndex或previousIndex呼叫被退回。)
所以如果你有列表中的一個以上的元素,它不會在新添加到末尾,但是在當前的和由next()
返回的之間。如果您確實想將新元素放在列表的末尾,請使用queue.add(...)
通常,在通過迭代器遍歷集合時修改集合並不可取,所以我建議您使用第二種方法(收集額外的元素在一個單獨的列表中,並將它們添加到原始結尾處)
只是好奇,你是否正式被要求不使用另一個列表? – UmNyobe 2012-04-27 11:27:14
沒有明顯的,但我想迭代時添加,因爲我需要在迭代期間處理新添加的元素,這可能是最短的方式。 – 2012-04-27 13:17:42
重複的https://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration有一些很好的答案。 – 2017-11-24 16:35:44