码迷,mamicode.com
首页 > 其他好文 > 详细

iterator

时间:2014-11-06 12:33:58      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   os   java   for   sp   div   on   

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

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

Java代码  bubuko.com,布布扣
  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在被创建的同时 会产生一个记录内存的内存目录表  指向对应的对象集合  一旦对象集合产生改变 而内存目录表没有改变会报错

iterator

标签:http   io   ar   os   java   for   sp   div   on   

原文地址:http://www.cnblogs.com/qzlpa/p/4078115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!