Iterator和fast-fail机制

在没有Iterator的情况下我们可以用for循环,那为什么我们要使用Iterator呢?

为什么需要迭代器Iterator?

迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。只要拿到这个对象,使用迭代器就可以遍历这个对象的内部。这么说到底是什么意思呢。比如我们已经了解了ArrayList和LinkedList集合的内部结构,那我们也就了解了它们的api的用途,就知道
arrayList.get(i)可以获取到元素也可以通过arrayList.remove()来删除元素。那现在有一个以前没有见过的集合UnkownCollection,如果要遍历它,我们首先想到的就是无查询该集合的API,那去查api也就相当于了解去了解结构了呀,之所以无法在不知道API或内部结构的时候获取元素是因为访问集合元素的逻辑与集合本身耦合度太高了,无法将访问逻辑从集合类和客户端中分离出来。那么迭代器就是为了将访问逻辑从集合类与客户端代码分离而出现的。

什么是迭代器呢?

迭代器我们可以简单的理解为遍历。是一个遍历各类容器里面的所有对象的标准。由于迭代器总是用同一种逻辑来遍历集合,因此只要该集合内部实现了迭代器就可以在不知道API或者集合内部结构的情况下通过迭代器遍历该集合的元素。
用ArrayList为例:我们对比一下用普通的for循环和迭代器之间的区别:
普通for循环:

 ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add("how are you");
        arrayList.add("I'm ok");
        //这里就需要了解arrayList的api和内部结构
           for(int i=0;i<arrayList.size();i++){
               String string=arrayList.get(i);
           }

使用迭代器:

 ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add("how are you");
        arrayList.add("I'm ok");
        Iterator<String> iterator=arrayList.iterator();
        while (iterator.hasNext()){
            String string=iterator.next();
        }

因为在java中迭代器提供一个标准化的接口:

public interface Iterator<E> {
//如果有更多的元素则返回true
  boolean hasNext();
//返回下一个元素,如果没有下一个元素则会抛出NoSuchElementException
 E next();
//如果当前迭代器不支持remove操作则抛出UnsupportedOperationException
//如果next方法还没有被调用或是在remove 方法调用之后再调用next 方法会抛出IllegalStateException异常
 default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}

大多数情况下我们一般只需要使用next(),hasNext()两个方法即可完成元素迭代。

在ArrayList中Iterator的实现

其中Itr是Arraylist的内部类

 private class Itr implements Iterator<E> {
        int cursor;       //下个返回元素的位置
        int lastRet = -1; // 上一个返回元素的位置; 如果是-1则一个表示没有这个元素
       //这个关于快速失败机制的实现,稍后会有讲解
        int expectedModCount = modCount;
    //如果下一个可返回元素位置不等于list的size(内部类可访问外部类的成员)
        public boolean hasNext() {
            return cursor != size;
        }
    <span class="hljs-meta">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
    <span class="hljs-function"><span class="hljs-keyword">public</span> E <span class="hljs-title">next</span><span class="hljs-params">()</span> </span>{
        checkForComodification();
        <span class="hljs-keyword">int</span> i = cursor;

//如果下一个元素的位置大于size则抛出NoSuchElementException
if (i >= size)
throw new NoSuchElementException();
//获取外部类ArrayList实例中的数据
Object[] elementData = ArrayList.this.elementData;
//快速失败机制
if (i >= elementData.length)
throw new ConcurrentModificationException();
//下一个可访问的元素位置+1
cursor = i + 1;
//返回值并给lastRet赋值
return (E) elementData[lastRet = i];
}

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">remove</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (lastRet &lt; <span class="hljs-number">0</span>)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        checkForComodification();

        <span class="hljs-keyword">try</span> {

//移除上一个返回 的元素
ArrayList.this.remove(lastRet);
//给下一个访问元素位置更新
cursor = lastRet;
//给上一个访问元素复原
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}

//快速失败机制的实现
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

这个源码比较简单易懂。
我们可以根据上面总结一下:

  • 迭代器Iterator内部最终操作的也是ArrayList的数组和方法
  • hasNext()通过curor判断将要被访问的元素是否存在
  • next()返回的正在被访问的元素,同时会保存该元素的下标指向lastRet,而cursor会指向下一下未被访问的元素。
  • remove()移除后数组需要移动,同时cursor指向需要更新为lastRet,因为lastRet此时代表着往前移动的元素。

快速失败(fast-fail)机制

刚刚上面有说

   int expectedModCount = modCount;
//快速失败机制的实现
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

在next和remove中都会调用这个checkForComodification这个方法。这样做是为什么呢?在上面我们看到我们通过 ArrayList的迭代器遍历元素的时候此时为调用next(),其内部还是用的ArrayList.this.elementData。

 Object[] elementData = ArrayList.this.elementData;

迭代器会先获取整个数组对象,然后进行取舍操作,但是在使用iterator的同时,假设我们又去操作调用了ArrayList本身的方法比如ArrayList.remove(index),那么elementData数组的元素就会发生变化,而迭代器也要通过hasNext()方法判断,正好调用next方法,但是数据发生了变化而造成了数据不一致的问题。那下面通过一个例子说明一下问题:

  ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add("how are you");
        arrayList.add("I'm ok");
        Iterator<String> iterator=arrayList.iterator();
        boolean shouldDelete=true;
        while (iterator.hasNext()){
            String string=iterator.next();
           if(shouldDelete){
               shouldDelete=!shouldDelete;
               arrayList.remove(2);
           }
        }

运行结果:

抛出异常

这就是我们的快速失败机制。
我们什么时候抛出ConcurrentModificationException呢?

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

就是每次在迭代器调用next()和remove()的时候都会先调用checkForComodification()方法,其中modCount是ArrayList中的成员变量。会次ArrayList在调用add(),remove(),clear(),ensureCapacity()这些会修改数据结构的方法中都会使modCount++。在获取迭代器的时候会把modCount赋值给迭代器的expectedModCount变量。此时modCount与expectedModCount肯定相等,在迭代元素的过程中如果ArrayList调用自身方法使集合发生变化,那么modCount肯定会变,此时modCount与expectedModCount肯定会不相等。在迭代过程中,只要发现modCount!=expectedModCount,则说明结构发生了变化也就没有必要继续迭代元素了。此时会抛出ConcurrentModificationException,终止迭代操作。这就是java JDK的常用的集合中的快速失败机制。

理解快速失败机制(fast-fail机制)

我们大概了解了快速失败机制的执行原理。重新整理一下快速失败机制,"快速失败"即fail-fast,它是java集合的一种错误检测机制。当多钱程对集合进行结构上的改变或者集合在迭代元素时直接调用自身方法改变集合结构而没有通知迭代器时,有可能会触发fast-fail机制并抛出异常。需要注意一点,有可能触发fast-fail机制而不是肯定。触发时机是在迭代过程中,集合的结构发生了变化而此时迭代器并不知道或者还没来得及反应时便会产生fail-fast机制。这里再次强调,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改或者自身修改做出任何硬性保证。快速失败迭代器会尽最大努力抛出 ConcurrentModificationException。
而我们把上面抛出异常的例子用迭代器的remove替换一下:

    ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add("how are you");
        arrayList.add("I'm ok");
        //这里就需要了解arrayList的api和内部结构
        Iterator<String> iterator=arrayList.iterator();
        boolean shouldDelete=true;
        while (iterator.hasNext()){
            String string=iterator.next();
           if(shouldDelete){
               shouldDelete=!shouldDelete;
               //arrayList.remove(2);
               iterator.remove();
           }
    }

这个时候程序运行就是正常的。并不会抛出异常。
在ArrayList中得到迭代器方法:

 public Iterator<E> iterator() {
        return new Itr();
    }

这是一个迭代器模式(游标模式)的应用
看到什么自己不懂的记下来。

      </div>

猜你喜欢

转载自blog.csdn.net/baidu_38634017/article/details/85340288