HashMap迭代器

HashMap的迭代器是强一致性的,但是我们又需要在迭代器遍历时删除元素呢? 调用迭代器的remove方法。

public static void useMap(final Map<String,Integer> scores) {
    scores.put("WU",19);
    scores.put("zhang",14);
    scores.put("sun",14);
    scores.put("zhou",14);
    try {
        Iterator<String> iterator = scores.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if(key.equals("sun")) {
                iterator.remove();  // 首先在迭代器中删除这个元素
            }
        }
        iterator = scores.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(key);
        }
    }catch (Exception ex) {
        System.out.println("fail:" + ex);
    }
}
public static void main(String[] args) {
    useMap(new HashMap<String, Integer>());
}
/*
zhang
zhou
WU
*/


abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    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)
            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;
    }

    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;
        //1 会调用HashMap的方法removeNode()进行删除,删除时,HashMap的modCount会增加
        removeNode(hash(key), key, null, false, false);
        //2 同时更新迭代器的expectedModCount,后续的遍历不会报错
        expectedModCount = modCount;
    }
}


转载于:https://my.oschina.net/u/1537182/blog/655857

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值