繁体   English   中英

即使使用iterator.remove()删除节点,HashMap也会引发ConcurrentModification

[英]HashMap throws ConcurrentModification even if using iterator.remove() to remove node

操作HashMap时出现ConcurrentModificationException 代码如下:

    Iterator<Integer> iterator =cacheMap.keySet().iterator();
        while(iterator.hasNext()) {
        if(iterator.next() == target) {
            iterator.remove();
        }
    }

我唯一使用的操作是这样删除和cacheMap.put(node) 这些方法都在主线程中调用,包括Activity onCreate() onPostExecute()方法, AsyncTask handleMessage(Message msg)方法和主线程处理程序中的handleMessage(Message msg)方法。

但是有时候,当我使用上述方法删除节点时,虽然它确实很少,但在iterator.next()抛出了ConcurrentModificationException

我已经审查了HashMap中的相关方法。 就像这样:

@Override public Set<K> keySet() {
    Set<K> ks = keySet;
    return (ks != null) ? ks : (keySet = new KeySet());
}

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

private abstract class HashIterator {
    int nextIndex;
    HashMapEntry<K, V> nextEntry = entryForNullKey;
    HashMapEntry<K, V> lastEntryReturned;
    int expectedModCount = modCount;

    HashIterator() {
        if (nextEntry == null) {
            HashMapEntry<K, V>[] tab = table;
            HashMapEntry<K, V> next = null;
            while (next == null && nextIndex < tab.length) {
                next = tab[nextIndex++];
            }
            nextEntry = next;
        }
    }

    public boolean hasNext() {
        return nextEntry != null;
    }

    HashMapEntry<K, V> nextEntry() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (nextEntry == null)
            throw new NoSuchElementException();

        HashMapEntry<K, V> entryToReturn = nextEntry;
        HashMapEntry<K, V>[] tab = table;
        HashMapEntry<K, V> next = entryToReturn.next;
        while (next == null && nextIndex < tab.length) {
            next = tab[nextIndex++];
        }
        nextEntry = next;
        return lastEntryReturned = entryToReturn;
    }

    public void remove() {
        if (lastEntryReturned == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        HashMap.this.remove(lastEntryReturned.key);
        lastEntryReturned = null;
        expectedModCount = modCount;
    }
}

@Override public V remove(Object key) {
    if (key == null) {
        return removeNullKey();
    }
    int hash = secondaryHash(key);
    HashMapEntry<K, V>[] tab = table;
    int index = hash & (tab.length - 1);
    for (HashMapEntry<K, V> e = tab[index], prev = null;
            e != null; prev = e, e = e.next) {
        if (e.hash == hash && key.equals(e.key)) {
            if (prev == null) {
                tab[index] = e.next;
            } else {
                prev.next = e.next;
            }
            modCount++;
            size--;
            postRemove(e);
            return e.value;
        }
    }
    return null;
}

private V removeNullKey() {
    HashMapEntry<K, V> e = entryForNullKey;
    if (e == null) {
        return null;
    }
    entryForNullKey = null;
    modCount++;
    size--;
    postRemove(e);
    return e.value;
}

/**
 * Subclass overrides this method to unlink entry.
 */
void postRemove(HashMapEntry<K, V> e) { }

调用nextEntry()remove时, expectedModeCount检查modCountnextEntry() 但是,如果调用iterator.remove()删除节点,则两个整数之差似乎是不可能的。

只需使用cacheMap.remove(target)。

从文档中:

public V remove(Object key)从此映射中删除指定键的映射(如果存在)。

记住,HashMap只能为一个给定的键存储一个对象,因此不需要遍历所有值。

您无法迭代集合并从其中删除项目。

采用:

Set<Integer> set = new HashSet<Integer>();
Iterator<Integer> iterator =cacheMap.keySet().iterator();
    while(iterator.hasNext()) {
        Integer key = iterator.next();
        if(key == target) {
            set.add(key );
        }
    }
    cacheMap.rmoveAll(set);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM