How to copy an iterator to another one?

后端 未结 3 1084
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 18:39

I need to iterate over the set of values for each iteration of for loop, but only for first iteration it works fine. Thereafter the itr.hasNext() returns

3条回答
  •  -上瘾入骨i
    2021-01-07 18:59

    You can only iterate an Iterator once.

    If you need to "reset" it, and recreating the Iterator is expensive (such as reading from a file), you could copy the data into a temporary Collection (such as an ArrayList). But that requires enough memory to hold everything at once.

    Another approach could be (depends on what your program does) to swap the order of loop nesting: Iterate over your iterator just once, and over your Persons in the inner loop (since you already have all those in memory). Obviously, this processes things in a different order which may or may not be easy to accomodate for you.

提交回复
热议问题