iterator

Posted on 2014-11-06 10:39  懒的小猫  阅读(130)  评论(0)    收藏  举报

iterator.next():方法  原理是将当前指针所指的元素锁定遍历,将指针移至下一个目标上。

看一段jdk中Interator.next()的实现源码,就会明白next()的真正作用了。
AbstractList中的内部类Itr部分源码如下:

Java代码  收藏代码
  1.    private class Itr implements Iterator<E> {  
  2. /** 
  3.  * Index of element to be returned by subsequent call to next. 
  4.  */  
  5. int cursor = 0;  
  6.   
  7. /** 
  8.  * Index of element returned by most recent call to next or 
  9.  * previous.  Reset to -1 if this element is deleted by a call 
  10.  * to remove. 
  11.  */  
  12. int lastRet = -1;  
  13.   
  14. public boolean hasNext() {  
  15.            return cursor != size();  
  16. }  
  17.   
  18. public E next() {  
  19.            checkForComodification();  
  20.     try {  
  21.     E next = get(cursor);  
  22.     lastRet = cursor++;  
  23.     return next;  
  24.     } catch (IndexOutOfBoundsException e) {  
  25.     checkForComodification();  
  26.     throw new NoSuchElementException();  
  27.     }  
  28. }  


从上面的源码可以看出,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()之后,指针往后移动过一次

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3