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
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()
.
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
.
注意:本文来自Hello, buddy!。本站无法对本文内容的真实性、完整性、及时性、原创性提供任何保证,请您自行验证核实并承担相关的风险与后果!
CoLaBug.com遵循[CC BY-SA 4.0]分享并保持客观立场,本站不承担此类作品侵权行为的直接责任及连带责任。您有版权、意见、投诉等问题,请通过[eMail]联系我们处理,如需商业授权请联系原作者/原网站。