如果你不能使用另一个列表,你可以通过保留通过迭代器处理的元素数量的计数来解决你的问题,并将其与列表的原始大小进行比较:所有新元素都将在列表的末尾,所以当你达到原始大小时,你可以结束你的循环。
LinkedList queue = new LinkedList(schedules);
int origSize = queue.size();
int currCount = 0;
ListIterator 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 queue = new LinkedList(schedules);
LinkedList addQueue = new LinkedList();
ListIterator iterator = queue.listIterator();
while (iterator.hasNext()) {
Schedule schedule = iterator.next();
if(condition)
addQueue.add(new Schedule());
}
queue.addAll(addQueue);另请注意iterator.add()
Inserts the specified element into the list (optional operation). The element is inserted immediately before the next element that would be returned by next, if any, and after the next element that would be returned by previous, if any. (If the list contains no elements, the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element. (This call increases by one the value that would be returned by a call to nextIndex or previousIndex.)
因此,如果列表中有多个元素,则不会将新元素添加到末尾,而是添加当前元素和next()返回的元素。如果您确实要将新元素放在列表的末尾,请使用queue.add(...)
一般来说,不建议在通过迭代器遍历它时修改集合,所以我建议你使用第二种方法(在单独的列表中收集额外的元素并在最后将它们添加到原始集合中)