Java which element in the ListIterator is considered previous?

 ̄綄美尐妖づ 提交于 2019-12-04 13:00:52

It's easiest to think of the cursor as being between two elements. So at the start, it's before dog. Calling next() returns dog, and moves it to between dog and cat, etc. You've finished iterating when the cursor is after snake.

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 either next() or previous(). 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:

A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Possible cursor positions are (denoted by the asterisks):

*     *     *     *     *     *     *
  dog   cat  fish  bird  frog  snake

The next function advances the cursor by one position and returns the element between:

BEFORE:
*     *     v     *     *     *     *
  dog   cat  fish  bird  frog  snake
AFTER:
*     *     *     v     *     *     *
  dog   cat  FISH  bird  frog  snake
RETURNED: fish

The previous function will move the cursor back and will return the element between:

BEFORE:
*     *     *     *     *     v     *
  dog   cat  fish  bird  frog  snake
AFTER:
*     *     *     *     v     *     *
  dog   cat  fish  bird  FROG  snake
RETURNED: frog
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!