public class CollectionTest2 {
public static void main(String[] args) {
Collection<Student> collection = new ArrayList<Student>();
Student student = new Student("aaaa", 12);
Student student2 = new Student("bbbb", 13);
Student student3 = new Student("cccc", 14);
Student student4 = new Student("dddd", 15);
collection.add(student);
collection.add(student2);
collection.add(student3);
collection.add(student4);
Iterator<Student> iterator = collection.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Iterator本来确定是一个接口,collection.iterator() 调用方法后返回的是一个接口类型
通过Debug可以看到AbstractList<E>的源代码的一部分
| 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;
/** * 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(); } } |
通过这个内部类实现的迭代器、重写里面的next()、hasNext()方法实现遍历
类Itr是Iterator<E>的实现类,所以返回的是class java.util.ArrayList$Itr
iterator就是class java.util.ArrayList$Itr的对象
多态的体现
最后
以上就是无语冥王星最近收集整理的关于Iterator背后的实现原理的全部内容,更多相关Iterator背后内容请搜索靠谱客的其他文章。
发表评论 取消回复