Why iterator.forEachRemaining doesnt remove element in the Consumer lambda?

后端 未结 1 1975
迷失自我
迷失自我 2021-01-02 03:17

Lets have a look at this example:

public class ListIteratorTest {
    public static void main(String[] args) {
        List list = new ArrayLis         


        
相关标签:
1条回答
  • 2021-01-02 03:26

    Updated thanks to @studro. See his comment below.

    The API documentation states:

    The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

    It seems like the "unspecified behavior" part also applies during this internal iteration.

    Granted, the documentation for forEachRemaining states that the behavior is equivalent to

    while (hasNext())
        action.accept(next());
    

    and if action::accept did in fact call iterator.remove() the above snippet should not throw any exception (if remove is a supported operation). This might be a documentation bug.

    0 讨论(0)
提交回复
热议问题