I'm currently trying to learn how to implement my own ListIterators. I have most of it implemented and ready to go, except I'm confused by the previous() method. By standard convention, can I get an explanation of how previous() is usually interpreted.
i.e.:
>cursor<
dog cat fish bird frog snake
According to Oracles Java Platform 7 API:
E previous()
Returns the previous element in the list and moves the cursor position backwards. This method may be called repeatedly to iterate through the list backwards, or intermixed with calls to next() to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)
What I don't quite understand is if previous() is called, does it return 'fish' or 'cat'.
I understand it in 2 ways:
1) 'fish' was the object that you were previously at
2) 'cat' is the object at the index numerically previous to the index of 'fish'
If previous returns 'fish', then does remove() actually remove the same element regardless of the direction of traversal?
It's easiest to think of the cursor as being between two elements. So at the start, it's before
dog
. Callingnext()
returnsdog
, and moves it to betweendog
andcat
, etc. You've finished iterating when the cursor is aftersnake
.So
next()
always returns the value after the cursor, and moves the cursor to the position after that.previous()
always returns the value before the cursor, and moves the cursor to the position before that.EDIT: As noted by David Conrad in comments:
remove()
always removes the last value that was returned by eithernext()
orprevious()
. That's probably the least obvious part, when it comes to the way I've explained it above... it's much easier to model that behaviour using the sort of "on item" cursor you've described.ListIterator
is tricky, because the pointer's definition is a little bit different.Java 7 documentation says:
Possible cursor positions are (denoted by the asterisks):
The
next
function advances the cursor by one position and returns the element between:The
previous
function will move the cursor back and will return the element between: