美文网首页
集合-ArrayList 源码解读-Iterator-02

集合-ArrayList 源码解读-Iterator-02

作者: 愤怒的奶牛 | 来源:发表于2019-08-28 22:46 被阅读0次

Iterator 集合中的迭代器

// 获取迭代器
  public Iterator<E> iterator() {
        return new Itr();
    }
/**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return,游标
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size; //是否还有元数
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i]; // 从数组中获取值
        }
}

相关文章

网友评论

      本文标题:集合-ArrayList 源码解读-Iterator-02

      本文链接:https://www.haomeiwen.com/subject/jotjectx.html