Java iterator pointer nextIndex

微信扫一扫,分享到朋友圈

Java iterator pointer nextIndex

Could you explain behaviour of Iterator result:

ArrayList list = new ArrayList(
            Arrays.asList( new String[] { "a", "b", "c", "d" } ) );
    int i = 0;
    ListIterator iterator = list.listIterator();
    while( iterator.hasNext() ) {
        if( ++i == 3 ) {
            System.out.println(
                    iterator.previous() + iterator.nextIndex() );
        }
        System.out.println( iterator.next() + iterator.nextIndex() );
    }

The output is: a1 b2 b1 b2 c3 d4 Why third output is “b1” but not “a1”? I figure the structure

0 1 2 3 element index

a b c d element value

See the Javadoc for
ListIterator

:

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()
.

And
ListIterator.previous()

:

Returns the previous element in the list and moves the cursor position backwards…
(Note that alternating calls to next
and previous
will return the same element repeatedly.)

You’re calling previous()
between b
and c
, which returns the previous element ( b
) and sets the cursor back one position (between a
and b
), so that nextIndex()
now returns 1
.

微信扫一扫,分享到朋友圈

Java iterator pointer nextIndex

InnoDB vs MyISAM insert query time

上一篇

iPhone XS Max拍照直男审美?直出大片!

下一篇

你也可能喜欢

Java iterator pointer nextIndex

长按储存图像,分享给朋友