Do we ever need to use Iterators on ArrayList?

前端 未结 6 1412
南旧
南旧 2020-12-13 22:00

Yesterday, when I was answering to question getting ConcurrentModificationException error while using iterator and remove I added a notice that

It\'s

6条回答
  •  青春惊慌失措
    2020-12-13 22:38

    You are probably talking about explicitly using an iterator (since the : operator is also using the iterator behind the scenes).

    Say you want to have two "pointers" going over the array but the speed depends on the actual element values. How would you do this without explicitly using iterators (and without elementAt of course).

    For example (pseudo code):

    element1 = first element;
    element2 = first element;
    while(element1.hasNext && element2.hasNext)
    {
        if(element1 * 2 < element)
        {
            element2 = element2.next;
        }
        else
        {
            element1 = element1.next;
        }
    
        //do something with the pair of elements
    }
    

提交回复
热议问题