java的Iterator源码浅析
Posted 乐之者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java的Iterator源码浅析相关的知识,希望对你有一定的参考价值。
在java的集合中,List接口继承Collection接口,AbstractList类实现了List接口,在AbstractList中的内部类Itr实现了Iterator接口
ArrayList实现List接口并继承AbstractList类,结构图如下:(图片出自网络)
Iterator接口源码:
public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
AbstractList的内部类Itr实现了Iterator接口,如下所示:
private class Itr implements Iterator<E> { /**元素的下标 * Index of element to be returned by subsequent call to next. */ int cursor = 0; /**上一个元素的下标。如果元素已被删除就设置为-1 * 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; /**允许修改的次数,违规操作会抛异常 * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; /*检查是否还有下一个元素*/ public boolean hasNext() { return cursor != size(); } /*光标下移,并且返回当前的元素*/ public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } /*移除元素*/ public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
ArrayList中的iterator()方法:
public Iterator<E> iterator() { return new Itr(); }
ArrayList中的内部类Itr源码功能类似于AbstractList的内部类Itr。
阅读了Iterator的源码,再回头看Iterator遍历List的过程,理解就会深刻很多。
List<String> list=new ArrayList<String>();
list.add("apple"); list.add("banana"); list.add("watermelon");
for (Iterator<String> iterator=list.iterator();iterator.hasNext();) {
System.out.println( iterator.next());
}
以上是关于java的Iterator源码浅析的主要内容,如果未能解决你的问题,请参考以下文章