Iterator的源码解析

Java里面的数组数据可以通过索引来获取,那么对象呢?也是通过索引吗?今天我们就来分析一下Java集合中获取集合对象的方法迭代-Iterator。
本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,该源码分析基于JDK1.8,分析工具,AndroidStudio,文章分析不足之处,还请指正!
一、简介
我们常常使用 JDK 提供的迭代接口进行 Java 集合的迭代。


Iterator iterator = list.iterator();
     while(iterator.hasNext()){
       String string = iterator.next();
       //do something
     }
上面便是迭代器使用的基本模板,迭代其实我们可以简单地理解为遍历,是一个标准化遍历各类容器里面的所有对象的方法类。它总是控制 Iterator,向它发送”向前”,”向后”,”取当前元素”的命令,就可以间接遍历整个集合。在 Java 中 Iterator 为一个接口,它只提供了迭代了基本规则:


  public interface Iterator<E> {
  //判断容器内是否还有可供访问的元素
  boolean hasNext();
  //返回迭代器刚越过的元素的引用,返回值是 E
  E next();
  //删除迭代器刚越过的元素
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }
}
上面便是迭代器的基本申明,我们通过具体的集合来分析。
二、集合分类
2.1 ArrayList的Iterator
我们通过分析ArrayList的源码可以知道,在 ArrayList 内部首先是定义一个内部类 Itr,该内部类实现 Iterator 接口,如下:


private class Itr implements Iterator<E> {
  //....
}
在内部类实现了Iterator接口,而ArrayList的Iterator是返回的它的内部类Itr,所以我们主要看看Itr是如何实现的。


public Iterator<E> iterator() {
  return new Itr();
}
接下来我们分析一下它的内部类Itr的实现方式。


private class Itr implements Iterator<E> {
 
  protected int limit = ArrayList.this.size;
 
  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 < limit;
  }
 
  @SuppressWarnings("unchecked")
  public E next() {
    if (modCount != expectedModCount)
      throw new ConcurrentModificationException();
    int i = cursor;
    if (i >= limit)
      throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
      throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i];
  }
 
  public void remove() {
    if (lastRet < 0)
      throw new IllegalStateException();
    if (modCount != expectedModCount)
      throw new ConcurrentModificationException();
 
    try {
      ArrayList.this.remove(lastRet);
      cursor = lastRet;
      lastRet = -1;
      expectedModCount = modCount;
      limit--;
    } catch (IndexOutOfBoundsException ex) {
      throw new ConcurrentModificationException();
    }
  }
 
  @Override
  @SuppressWarnings("unchecked")
  public void forEachRemaining(Consumer<? super E> consumer) {
    Objects.requireNonNull(consumer);
    final int size = ArrayList.this.size;
    int i = cursor;
    if (i >= size) {
      return;
    }
    final Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length) {
      throw new ConcurrentModificationException();
    }
    while (i != size && modCount == expectedModCount) {
      consumer.accept((E) elementData[i++]);
    }
    // update once at end of iteration to reduce heap write traffic
    cursor = i;
    lastRet = i - 1;
 
    if (modCount != expectedModCount)
      throw new ConcurrentModificationException();
  }
}
首先我们来分析一下定义的变量:


protected int limit = ArrayList.this.size;
 
int cursor;    // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
其中,limit是当前ArrayList的大小,cursor代表的是下一个元素的索引,而lastRet是上一个元素的索引,没有的话就返回-1,expectedModCount没什么多大用处。我们接着分析看迭代的时候怎么判断有没有后继元素的。


public boolean hasNext() {
    return cursor < limit;
}
很简单,就是判断下一个元素的索引有没有到达数组的容量大小,达到了就没有了,到头了!
接着,我们在分析一下获取当前索引的元素的方法next


public E next() {
  if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
  int i = cursor;
  if (i >= limit)
    throw new NoSuchElementException();
  Object[] elementData = ArrayList.this.elementData;
  if (i >= elementData.length)
    throw new ConcurrentModificationException();
  cursor = i + 1;
  return (E) elementData[lastRet = i];
}
在next方法中为什么要判断modCount呢?即用来判断遍历过程中集合是否被修改过。modCount 用于记录 ArrayList 集合的修改次数,初始化为 0,,每当集合被修改一次(结构上面的修改,内部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不变,则表示集合内容没有被修改。该机制主要是用于实现 ArrayList 集合的快速失败机制,在 Java 的集合中,较大一部分集合是存在快速失败机制的。所以要保证在遍历过程中不出错误,我们就应该保证在遍历过程中不会对集合产生结构上的修改(当然 remove 方法除外),出现了异常错误,我们就应该认真检查程序是否出错而不是 catch 后不做处理。上面的代码比较简单,就是返回索引处的数组值。
对于ArrayList的迭代方法,主要是判断索引的值和数组的大小进行比较,看看还没有数据可以遍历了,然后再依次获取数组中的值,而已,主要抓住各个集合的底层实现方式即可进行迭代。
接下来我们在分析一下HashMap的Iterator的方法,其他方法类似,只要抓住底层实现方式即可。
2.2 HashMap的Iterator
在HashMap中,也有一个类实现了Iterator接口,只不过是个抽象类,HashIterator,我们来看看它的实现方式。


private abstract class HashIterator<E> implements Iterator<E> {
   HashMapEntry<K,V> next;    // next entry to return
   int expectedModCount;  // For fast-fail
   int index;       // current slot
   HashMapEntry<K,V> current;   // current entry
 
   HashIterator() {
     expectedModCount = modCount;
     if (size > 0) { // advance to first entry
       HashMapEntry[] t = table;
       while (index < t.length && (next = t[index++]) == null)
         ;
     }
   }
 
   public final boolean hasNext() {
     return next != null;
   }
 
   final Entry<K,V> nextEntry() {
     if (modCount != expectedModCount)
       throw new ConcurrentModificationException();
     HashMapEntry<K,V> e = next;
     if (e == null)
       throw new NoSuchElementException();
 
     if ((next = e.next) == null) {
       HashMapEntry[] t = table;
       while (index < t.length && (next = t[index++]) == null)
         ;
     }
     current = e;
     return e;
   }
 
   public void remove() {
     if (current == null)
       throw new IllegalStateException();
     if (modCount != expectedModCount)
       throw new ConcurrentModificationException();
     Object k = current.key;
     current = null;
     HashMap.this.removeEntryForKey(k);
     expectedModCount = modCount;
   }
 }
同样,它也定义了一个变量


HashMapEntry<K,V> next;    // next entry to return
int expectedModCount;  // For fast-fail
int index;       // current slot
HashMapEntry<K,V> current;   // current entry
next代表下一个entry的节点,expectedModCount同样是用于判断修改状态,用于集合的快速失败机制。index代表当前索引,current当前所索引所代表的节点entry,我们来看看如何判断是否还有下一个元素的值的。
public final boolean hasNext() {
  return next != null;
}
很简单就是判断next是否为null,为null的话就代表没有数据了。
接着分析获取元素的方法


final Entry<K,V> nextEntry() {
  if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
  HashMapEntry<K,V> e = next;
  if (e == null)
    throw new NoSuchElementException();
  // 一个Entry就是一个单向链表
  // 若该Entry的下一个节点不为空,就将next指向下一个节点;
  // 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。
  if ((next = e.next) == null) {
    HashMapEntry[] t = table;
    while (index < t.length && (next = t[index++]) == null)
      ;
  }
  current = e;
  return e;
}



LinkedList中Iterator源码分析:

private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;//下次元素的前一个元素
        private int nextIndex;//记录当前反问的位置
        private int expectedModCount = modCount;


        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }


        public boolean hasNext() {
            return nextIndex < size;
        }


        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();


            lastReturned = next;//记录上一次位置
            next = next.next;//下移
            nextIndex++;
            return lastReturned.item;
        }


        public boolean hasPrevious() {
            return nextIndex > 0;
        }


        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();


            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }


        public int nextIndex() {
            return nextIndex;
        }


        public int previousIndex() {
            return nextIndex - 1;
        }


        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();


            Node<E> lastNext = lastReturned.next;//删掉数据只需让它的上一个next引用指向它的next.next
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }


        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }


        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }


        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }


        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }



以上便是一些具体集合实例的迭代方法实现原理,同理可以分析其他集合的实现方式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值