Search code examples
javalistcollectionsiterator

How does the first call to previous returns the same element as the last call to next?


I'm reading Java Tutorial Oracle on List interface and have encountered the following statement:

Calls to next and previous can be intermixed, but you have to be a bit careful. The first call to previous returns the same element as the last call to next.

I'm struggling to get my head around the phrase: The first call to previous returns the same element as the last call to next. Could someone explain it in a bit more detail?


Solution

  • The first call to previous returns the same element as the last call to next. Could someone explain it in a bit more detail?

    If you say .next() and then .previous(), you get the same instance because of the internal position of the Iterator. Otherwise, consecutive calls to .next() would return the same instance.

    a b c
      ^
    

    .next() gives b, but moves the pointer to c

    a b c
        ^
    

    so .previous() then yields b.