美文网首页程序员
Java集合-Iterator(fast-fail)

Java集合-Iterator(fast-fail)

作者: 懒懒惰惰 | 来源:发表于2017-08-24 11:27 被阅读55次

之前分析了一些常用的集合,都绕过了迭代器这个概念,这里重点分析一下迭代器相关的知识点。这里首先分析一下ArrayList的迭代器。

Iterator

首先看一下Iterator的定义:

public interface Iterator<E> {
    
    boolean hasNext();

    E next();

    void remove();
}

简单的定义了Iterator的作用,就是一个迭代器,迭代器最重要的就是两个方法,判断是否有写一个元素hasNext(),和获取下一个元素next()。

接下来,会以ArrayList为例,介绍Iterator,下面是会以ArrayList为例的介绍Iterator定义:

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;
}

该Iterator继承了AbstractList的Iterator,其中cursor表示指向下一个元素的游标,lastRet指向上一个放回元素的游标,初始情况下,lastRet没有曾经返回元素,所以初始化为-1,如图:


ArrayList的Iterator

在每次迭代以前首先需要判断当前是否还有未迭代的元素hasNext:

public boolean hasNext() {
        return cursor != size;
    }

当游标顺序循环迭代,迭代完最后一个元素时,游标的位置如图:


遍历完所有元素

此时的cursor指向数组的位置值恰好等于size,所以此时没有下一个元素可供迭代提取。

接下来看最重要的next()方法:

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];
}

首先checkForComodification()方法是运用了fast-fail机制,后面会单独分析;然后:

int i = cursor;
if (i >= size)
    throw new NoSuchElementException();

将当前游标值存入到临时变量i,并判断游标值是否大于等于size的大小(判断依据参考上面所说的hasNext()),判断游标是否越界了;接着:

cursor = i + 1;
return (E) elementData[lastRet = i];

游标右移一位,同时返回原游标位置的元素,并把lastRet右移一位:

next

在List中,还定义了一个ListIterator, 他额外实现了向前查找元素,和添加元素的方法,总体来看,在实现原理上可以参考Iterator,这里就不重复分析了

fast-fail

快速失败机制,在上面分析中提到了一个方法checkForComodification(),运用的就是快速失败机制,那么在容器的jdk中能够经常看到以下一段话(摘自arrayList):

 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw {@code ConcurrentModificationException} on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness:  <i>the fail-fast behavior of iterators
 * should be used only to detect bugs.</i>

上面大概是说当并发迭代和结构修改时,迭代器会尽最大努力抛出 ConcurrentModificationException;具体举例说,当线程A获取当前容器的迭代器后,线程B对当前容器添加了一个元素(修改元素数据不会改变结构),线程A的跌打器就会检测到数据结构被变更,并抛出ConcurrentModificationException。这就是fast-fail机制。
那么具体实现还是看ArrayList的代码:

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

获取迭代器的时候,迭代器会得到当前容器的modCount修改次数,当每次检查时,只需要看原来的修改次数是否与当前相同,就可以知道,容器是否结构变更了。

for each

在jdk1.5以后,提供了对Collection的for each操作,通过使用for each的字节码可以看到,for each实际是调用了iterator的实现去实现的,这里就不重点分析字节码。这边看一下HashMap的for each的三种实现:

public Set<K> keySet() {
    Set<K> ks = keySet;
    return (ks != null ? ks : (keySet = new KeySet()));
}
public Collection<V> values() {
    Collection<V> vs = values;
    return (vs != null ? vs : (values = new Values()));
}
public Set<Map.Entry<K,V>> entrySet() {
        return entrySet0();
}

private Set<Map.Entry<K,V>> entrySet0() {
    Set<Map.Entry<K,V>> es = entrySet;
    return es != null ? es : (entrySet = new EntrySet());
}

分别是遍历键、值、键值对的方式,很多情况下,容易值遍历key再取通过可以找value的情况,这样的话,就多了一步get的过程,不如直接通过获取entryset的效率高,需要注意就是这个情况。

相关文章

网友评论

    本文标题:Java集合-Iterator(fast-fail)

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