开发者

trouble using ListIterator for a LinkedList in java

开发者 https://www.devze.com 2023-01-05 18:36 出处:网络
Is it possible to iterate through a LL in Java using a ListIterator, add objects periodically to the list, and process these items in the list in the order they were added?

Is it possible to iterate through a LL in Java using a ListIterator, add objects periodically to the list, and process these items in the list in the order they were added?

Let's say I start with a LL with a single object in it. I process this object, and decide I want to add two additional objects, which I wan开发者_StackOverflow社区t to further process (like FIFO). Intuitively, I start the process with

while (itr.hasNext()) {
itr.next();
...
itr.add();
}

However, this seems to quickly crumble - add actually adds items BEFORE the index I currently am at, and not after (ListIterator javadoc). This means when I hit the while loop start again, it actually doesn't recognize that stuff was added to the LL, because it actually needs to go BACKWARDS (.hasPrevious() instead of .hasNext()) to find it. But I can't start the LL with .hasPrevious() (i don't think) because the first item in the LL is a .next() item.

How does one cleanly do this? Or am i just being stupid?


You didn't quote the entire definition in your comment above:

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.)

The new item is inserted so that you have to call previous() to get it.

If you have to insert the item at the current iteration point, then you will have to do the management yourself and call previous(), which will involve restructuring the loop somewhat.

If you can add the new items to the end of the list and process them later, use a Queue implementation instead.


If you aren't going to be doing any removing in the loop, you could call previous() once per call to add() at the end of the loop body. This would leave the cursor before the first added item, which would then be returned by next() on the next iteration. I have to say, I feel like there must be a better way of doing this processing though.


I believe you have to separate adding to the list and iterating through it.

0

精彩评论

暂无评论...
验证码 换一张
取 消