ITPub博客

首页 > 应用开发 > Java > JDK7集合框架源码学习-ArrayList(3)迭代器

JDK7集合框架源码学习-ArrayList(3)迭代器

原创 Java 作者:壹頁書 时间:2016-07-08 16:53:36 0 删除 编辑
ArrayList实现了ListIterator接口

  1. public interface ListIterator<E> extends Iterator<E> {  
  2.     boolean hasNext();  
  3.     E next();  
  4.     boolean hasPrevious();  
  5.     E previous();  
  6.     int nextIndex();  
  7.     int previousIndex();  
  8.     void remove();  
  9.     void set(E e);  
  10.     void add(E e);  
  11. }  

这个接口在Iterator接口的基础上,可以查找前驱和后继节点.还能添加和修改.

ArrayList的ListIterator实现.
  1. private class ListItr extends Itr implements ListIterator<E> {  
  2.       ListItr(int index) {  
  3.           super();  
  4.           cursor = index;  
  5.       }  
  6.   
  7.       public boolean hasPrevious() {  
  8.           return cursor != 0;  
  9.       }  
  10.   
  11.       public int nextIndex() {  
  12.           return cursor;  
  13.       }  
  14.   
  15.       public int previousIndex() {  
  16.           return cursor - 1;  
  17.       }  
  18.   
  19.       @SuppressWarnings("unchecked")  
  20.       public E previous() {  
  21.           checkForComodification();  
  22.           int i = cursor - 1;  
  23.           if (i < 0)  
  24.               throw new NoSuchElementException();  
  25.           Object[] elementData = ArrayList.this.elementData;  
  26.           if (i >= elementData.length)  
  27.               throw new ConcurrentModificationException();  
  28.           cursor = i;  
  29.           return (E) elementData[lastRet = i];  
  30.       }  
  31.   
  32.       public void set(E e) {  
  33.           if (lastRet < 0)  
  34.               throw new IllegalStateException();  
  35.           checkForComodification();  
  36.   
  37.           try {  
  38.               ArrayList.this.set(lastRet, e);  
  39.           } catch (IndexOutOfBoundsException ex) {  
  40.               throw new ConcurrentModificationException();  
  41.           }  
  42.       }  
  43.   
  44.       public void add(E e) {  
  45.           checkForComodification();  
  46.   
  47.           try {  
  48.               int i = cursor;  
  49.               ArrayList.this.add(i, e);  
  50.               cursor = i + 1;  
  51.               lastRet = -1;  
  52.               expectedModCount = modCount;  
  53.           } catch (IndexOutOfBoundsException ex) {  
  54.               throw new ConcurrentModificationException();  
  55.           }  
  56.       }  
  57.   }  

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2121743/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 内部类总结
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339927