Java集合框架分析(六)-Iterator迭代器分析

本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,该源码分析基于JDK1.8,分析工具,AndroidStudio,文章分析不足之处,还请指正!数组

Java里面的数组数据能够经过索引来获取,那么对象呢?也是经过索引吗?今天咱们就来分析一下Java集合中获取集合对象的方法迭代-Iterator。bash

简介

咱们经常使用 JDK 提供的迭代接口进行 Java 集合的迭代。框架

Iterator iterator = list.iterator();
         while(iterator.hasNext()){
             String string = iterator.next();
             //do something
         }
复制代码

上面即是迭代器使用的基本模板,迭代其实咱们能够简单地理解为遍历,是一个标准化遍历各种容器里面的全部对象的方法类。它老是控制 Iterator,向它发送”向前”,”向后”,”取当前元素”的命令,就能够间接遍历整个集合。在 Java 中 Iterator 为一个接口,它只提供了迭代了基本规则:ide

public interface Iterator<E> {
    //判断容器内是否还有可供访问的元素
    boolean hasNext();
	//返回迭代器刚越过的元素的引用,返回值是 E
    E next();
	//删除迭代器刚越过的元素
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}
复制代码

上面即是迭代器的基本申明,咱们经过具体的集合来分析。工具

集合分类

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的实现方式。ui

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();
       }
   }
复制代码

首先咱们来分析一下定义的变量:this

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没什么多大用处。咱们接着分析看迭代的时候怎么判断有没有后继元素的。spa

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的方法,其余方法相似,只要抓住底层实现方式便可。

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;
      }
复制代码

以上即是一些具体集合实例的迭代方法实现原理,同理能够分析其余集合的实现方式。

关于做者

专一于 Android 开发多年,喜欢写 blog 记录总结学习经验,blog 同步更新于本人的公众号,欢迎你们关注,一块儿交流学习~

在这里插入图片描述
相关文章
相关标签/搜索