首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使使用iterator.remove()删除节点,HashMap也会抛出ConcurrentModification

即使使用iterator.remove()删除节点,HashMap也会抛出ConcurrentModification
EN

Stack Overflow用户
提问于 2014-11-26 15:28:38
回答 2查看 164关注 0票数 2

我在操作HashMap时遇到了ConcurrentModificationException。代码如下:

代码语言:javascript
复制
    Iterator<Integer> iterator =cacheMap.keySet().iterator();
        while(iterator.hasNext()) {
        if(iterator.next() == target) {
            iterator.remove();
        }
    }

我使用的唯一操作是remove like that和cacheMap.put(node)。这些方法都是在主线程中调用的,包括ActivityonCreate()方法、AsyncTaskonPostExecute()方法和主线程处理程序中的handleMessage(Message msg)方法。

但是,当我使用上面的方法删除节点时,偶尔会在iterator.next()中抛出ConcurrentModificationException,尽管它确实很少。

我已经回顾了HashMap中的相关方法。它是这样的:

代码语言:javascript
复制
@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时,检查modCountexpectedModeCount。但是,如果调用iterator.remove()删除节点,则两个整数的差值似乎是不可能的。

EN

回答 2

Stack Overflow用户

发布于 2014-11-26 17:25:45

只要使用cacheMap.remove(目标)即可。

从文档中:

public V remove(对象键)从该映射中删除指定键的映射(如果存在)。

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

票数 1
EN

Stack Overflow用户

发布于 2014-11-26 15:51:11

不能迭代集合并从中移除项。

使用:

代码语言:javascript
复制
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);
票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27143444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档