• 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());
    }
  • 相关阅读:
    linux 操作系统 基础
    [HAOI2011]Problem A
    [HNOI2015] 菜肴制作
    [P3676]小清新数据结构题
    [NOI2016]区间
    [BOI2007]Mokia 摩基亚
    [NOI2012]美食节
    [CQOI2015]网络吞吐量
    [六省联考2017]期末考试
    [HNOI2015]亚瑟王
  • 原文地址:https://www.cnblogs.com/expiator/p/6125141.html
Copyright © 2020-2023  润新知