深入扒 HashMap 源码 - 6.4 HashMap 内部类迭代器 HashIterator、KeyIterator、ValueIterator、EntryIterator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ocp114/article/details/82916011

KeyIterator、ValueIterator、EntryIterator 都继承于 HashIterator 以及实现了 Iterator,只在内部有部分差异,KeyIterator 的 next() 方法获取的是 key,ValueIterator 的是 value,EntryIterator 是 node
下面看代码实现

abstract class HashIterator {
	// 在当前已读到的元素的下一个元素
    Node<K,V> next;        // next entry to return
    // 当前已读到的元素
    Node<K,V> current;     // current entry
    // 期望操作数,用于多线程情况下,如果多个线程同时对 HashMap 进行读写,
    // 那么这个期望操作数 expectedModCount 和 HashMap 的 modCount 就会不一致,这时候抛个异常出来,称为“快速失败”
    int expectedModCount;  // for fast-fail
    // 当前正在迭代的桶位置索引
    int index;             // current slot
    
    HashIterator() {
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
        // 找到第一个不为空的桶的索引
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

    // 判断是否有下一个节点
    public final boolean hasNext() {
        return next != null;
    }

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        // 这里就是快速失败实现的地方,可以看出,多线程情况下,执行到 if (modCount != expectedModCount) 这行代码时
        // 有可能这时候  modCount 还是等于 expectedModCount,当过了这一行代码,modCount 有可能不等于 expectedModCount
        // 所以对于这个时候会有一个时差,或许会读到有问题的数据
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        // 当前的桶遍历完了就开始遍历下一个桶
        if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    // 和外部 remove(Object key) 差不多,但是不会对 table 的元素进行重排,所以这个方法适合一边迭代一边删除元素
    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        // 快速失败
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        // 移除操作会使得 HashMap 产生操作数,所以操作完后需要更新一下期望操作数 expectedModCount
        expectedModCount = modCount;
    }
}

final class KeyIterator extends HashIterator implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

final class ValueIterator extends HashIterator implements Iterator<V> {
    public final V next() { return nextNode().value; }
}

final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

这里面个人觉得比较巧妙的就是快速失败了,对于性能的提高有很大帮助,另外就是一个一个桶去遍历了

猜你喜欢

转载自blog.csdn.net/ocp114/article/details/82916011