0

Could you explain behaviour of Iterator result:

    ArrayList< String > list = new ArrayList< >(
            Arrays.asList( new String[] { "a", "b", "c", "d" } ) );
    int i = 0;
    ListIterator< String > 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

3
  • nextIndex is the index that would be returned by calling next(). Does that answer your question? Commented Jul 10, 2016 at 19:19
  • @BoristheSpider I have a bit change the question Commented Jul 10, 2016 at 19:23
  • 1
    BTW: you don't need the new String[] { ... }, you can simply use Arrays.asList("a", "b", "c", "d"). Commented Jul 10, 2016 at 20:44

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I think it's best explained by viewing the index values as the dividing lines between the elements:

values:  | a | b | c | d |
indizes: 0   1   2   3   4

next() returns the element to the right of the index position and increments the index. previous() returns the element to the left of the index position and decrements the index.

So in the first iteration, index is 0, so next() returns a and updates the index to 1.

In the second iteration, index is 1, so next() returns b and updates the index to 2.

In the third iteration, you first call previous(), which returns b (left of the position 2) and updates the index to 1 (which is returned by nextIndex()).

Then you call next(), which returns b again (right of the position 1) and updates the index to 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.