iterator.next():方法 原理是将当前指针所指的元素锁定遍历,将指针移至下一个目标上。
看一段jdk中Interator.next()的实现源码,就会明白next()的真正作用了。
AbstractList中的内部类Itr部分源码如下:
- private class Itr implements Iterator<E> {
- /**
- * Index of element to be returned by subsequent call to next.
- */
- int cursor = 0;
- /**
- * Index of element returned by most recent call to next or
- * previous. Reset to -1 if this element is deleted by a call
- * to remove.
- */
- int lastRet = -1;
- public boolean hasNext() {
- return cursor != size();
- }
- public E next() {
- checkForComodification();
- try {
- E next = get(cursor);
- lastRet = cursor++;
- return next;
- } catch (IndexOutOfBoundsException e) {
- checkForComodification();
- throw new NoSuchElementException();
- }
- }
从上面的源码可以看出,next()方法获取的是当前cursor对应的元素值(通过get方法),而默认初始化会将cursor设置为0,所以
第一次调用next()方法返回的是get(0)。如果初始化Interator的实现类时指定相应的index值,则第一次调用next()方法放回的
是get(index)。
iterator在被创建的同时 会产生一个记录内存的内存目录表 指向对应的对象集合 一旦对象集合产生改变 而内存目录表没有改变会报错
.next():返回当前的值,并且指针往后移动一个对象
public int nextIndex()
{
return this.cursor;
}
public int previousIndex()
{
return (this.cursor - 1);
}
。nextIndex():当使用next()之后,指针已经往后移动一个 所以是当前使用next()方法的最后一个参数的后一个对象的位置
.previousIndex():当使用next()之后,使用该方法会回到当前对象的位置上,原因是在调用next()之后,指针往后移动过一次
浙公网安备 33010602011771号