遍历并remove HashMap中的元素时,遇到ConcurrentModificationException

for (Map.Entry<ImageView, UserConcise> peer : mPortraitViewPeers.entrySet()) {   
  1. ImageView key = peer.getKey();
  2. key.setImageBitmap(peer.getValue().getProfile_image());
  3. mPortraitViewPeers.remove(key);
  4. }
for (Map.Entry<ImageView, UserConcise> peer : mPortraitViewPeers.entrySet()) {
ImageView key = peer.getKey();
key.setImageBitmap(peer.getValue().getProfile_image());
mPortraitViewPeers.remove(key);
}

在查看一些资料后,修改的代码

  1. Iterator<Map.Entry<ImageView, UserConcise>> iterator = mPortraitViewPeers.entrySet().iterator();
  2. while (iterator.hasNext()) {
  3. Map.Entry<ImageView, UserConcise> entry = iterator.next();
  4. ImageView key = entry.getKey();
  5. key.setImageBitmap(entry.getValue().getProfile_image());
  6. iterator.remove();
  7. }
Iterator<Map.Entry<ImageView, UserConcise>> iterator = mPortraitViewPeers.entrySet().iterator();

while (iterator.hasNext()) {
Map.Entry<ImageView, UserConcise> entry = iterator.next();
ImageView key = entry.getKey();
key.setImageBitmap(entry.getValue().getProfile_image());
iterator.remove();
}

以下是网上的解释

  1. java.util.ConcurrentModificationException
  2. 工作中碰到个ConcurrentModificationException。代码如下:
  3. List list = ...;
  4. for(Iterator iter = list.iterator(); iter.hasNext();) {
  5. Object obj = iter.next();
  6. ...
  7. if(***) {
  8. list.remove(obj);
  9. }
  10. }
  11. 在执行了remove方法之后,再去执行循环,iter.next()的时候,报java.util.ConcurrentModificationException(当然,如果remove的是最后一条,就不会再去执行next()操作了)
  12. 下面来看一下源码
  13. public interface Iterator<E> {
  14. boolean hasNext();
  15. E next();
  16. void remove();
  17. }
  18. public interface Collection<E> extends Iterable<E> {
  19. ...
  20. Iterator<E> iterator();
  21. boolean add(E o);
  22. boolean remove(Object o);
  23. ...
  24. }
  25. 这里有两个remove方法
  26. 接下来来看看AbstractList
  27. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
  28. //AbstractCollection和List都继承了Collection
  29. protected transient int modCount = 0;
  30. private class Itr implements Iterator<E> {  //内部类Itr
  31. int cursor = 0;
  32. int lastRet = -1;
  33. int expectedModCount = modCount;
  34. public boolean hasNext() {
  35. return cursor != size();
  36. }
  37. public E next() {
  38. checkForComodification();  //特别注意这个方法
  39. try {
  40. E next = get(cursor);
  41. lastRet = cursor++;
  42. return next;
  43. } catch(IndexOutOfBoundsException e) {
  44. checkForComodification();
  45. throw new NoSuchElementException();
  46. }
  47. }
  48. public void remove() {
  49. if (lastRet == -1)
  50. throw new IllegalStateException();
  51. checkForComodification();
  52. try {
  53. AbstractList.this.remove(lastRet);  //执行remove对象的操作
  54. if (lastRet < cursor)
  55. cursor--;
  56. lastRet = -1;
  57. expectedModCount = modCount;  //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
  58. } catch(IndexOutOfBoundsException e) {
  59. throw new ConcurrentModificationException();
  60. }
  61. }
  62. final void checkForComodification() {
  63. if (modCount != expectedModCount)  //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
  64. throw new ConcurrentModificationException();
  65. }
  66. }
  67. }
  68. remove(Object o)在ArrayList中实现如下:
  69. public boolean remove(Object o) {
  70. if (o == null) {
  71. for (int index = 0; index < size; index++)
  72. if (elementData[index] == null) {
  73. fastRemove(index);
  74. return true;
  75. }
  76. } else {
  77. for (int index = 0; index < size; index++)
  78. if (o.equals(elementData[index])) {
  79. fastRemove(index);
  80. return true;
  81. }
  82. }
  83. return false;
  84. }
  85. private void fastRemove(int index) {
  86. modCount++;  //只增加了modCount
  87. ....
  88. }
  89. 所以,产生ConcurrentModificationException的原因就是:
  90. 执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
  91. 要避免这个Exception,就应该使用remove()方法。
  92. 这里我们就不看add(Object o)方法了,也是同样的原因,但没有对应的add()方法。一般嘛,就另建一个List了
  93. 下面是网上的其他解释,更能从本质上解释原因:
  94. Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
  95. 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。

遍历并remove HashMap中的元素时,遇到ConcurrentModificationException的更多相关文章

  1. list,set等集合遍历时,不能remove集合中的元素。需要new一个Object或者list,set,里面add需要删除的元素,等集合遍历完了进行remove(Object)或者removeAll(list/set)操作

    list,set等集合遍历时,不能remove集合中的元素.需要new一个Object或者list,set,里面add需要删除的元素,等集合遍历完了进行remove(Object)或者removeAl ...

  2. 修改NSMutableArray中的元素时的注意事项

    最近做项目遇到从文件加载数组,并对数组中的元素进行操作的问题,特意写了个Demo,记录下要注意的东西: 代码如下: NSArray *array = @["]; NSMutableArray ...

  3. Java 循环遍历删除set list中的元素

    删除List和Set中的某些元素 错误代码的写法: Set<String> set = new HashSet<String>(); set.add("aaaaaa& ...

  4. 整理悬浮在列表中a元素时改变a元素上下边框颜色的问题。

    整理一下当悬浮在a元素上时a的上下边颜色改变,并且里面的内容不会移动,下面是PSD图效果区域: 刚开始我先给A元素加了上下边框和颜色,利用a:hover改变a元素上下的边框颜色,但是第一个a元素的下边 ...

  5. 遍历std::list过程中删除元素后继续遍历过程

    std::list::erase Erase elements Removes from the list container either a single element (position) o ...

  6. C#实现在foreach遍历中删除集合中的元素(方法总结)

    目录 方法一:采用for循环,并且从尾到头遍历 方法二:使用递归 方法三:通过泛型类实现IEnumerator 在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致 ...

  7. [改善Java代码]减少HashMap中元素的数量

    在系统开发中我们经常会使用HashMap作为数据集容器,或者是用缓冲池来处理,一般很稳定,但偶尔也会出现内存溢出的问题(OutOfMemory错误),而且这经常是与HashMap有关的.而且这经常是与 ...

  8. 当JAVA集合移除自身集合元素时发生的诸多问题

    一段代码目的是想删除集合中包括"a"字符串的集合项: public class TestForeach { public static void main(String[] arg ...

  9. 【java基础 12】HashMap中是如何形成环形链表的?

    导读:经过前面的博客总结,可以知道的是,HashMap是有一个一维数组和一个链表组成,从而得知,在解决冲突问题时,hashmap选择的是链地址法.为什么HashMap会用一个数组这链表组成,当时给出的 ...

随机推荐

  1. wxPython + Boa 练习程序

    最近需要做点支持linux的跨平台gui,网上查到了wxPython及Boa,感觉不错,照着Boa文档做做练习. 代码: App: #!/usr/bin/env python #Boa:App:Boa ...

  2. PySide 简易教程<二>-------工欲善其事,必先利其器

    OK , 在Linux的开发环境下,对于我们的简短的PySide程序而言,不需要使用QtCreator,使用文本编辑器.之所以,使用文本编辑器,是因为小应用代码量很少,更重要的是一行行的写可以加深我们 ...

  3. JMS之开源实现ActiveMQ

    1.ActiveMQ是开源的JMS实现. 可以把不影响用户执行结果又比较耗时的任务(比如发邮件通知管理员)异步的扔给jms 服务端,而尽快的把屏幕返还给用户,且服务端能够多线程排队响应高并发的请求.可 ...

  4. Linux nmon 监控工具使用

    Linux 系统下监控指标及指标查看 一.工具介绍     Linux 系统下资源监控使用nmon 工具.它可以帮助在一个屏幕上显示所有重要的性能优化信息,并动态地对其进行更新且并不会消耗大量的CPU ...

  5. php获取指定日期所在星期的开始时间与结束时间

    function getWeekRange($date){    $ret=array();    $timestamp=strtotime($date);    $w=strftime('%u',$ ...

  6. NOSQL的应用,Redis/Mongo

    NOSQL的应用,Redis/Mongo 1.心路历程 上年11月份来公司了,和另外一个同事一起,做了公司一个移动项目的微信公众号,然后为了推广微信公众号,策划那边需要我们做一些活动,包括抽奖,投票. ...

  7. 关于sublime text

    Sublime text2 C/C++ 编译环境设置 (2014-04-10 20:51:16) 转载▼ 标签: sublime c语言 程序设计 gcc cpp 分类: 记录与分享 sublime ...

  8. ios 框架学习笔记

    ios主要的系统层次: 一.Cocoa Touch 层:创建应用程序主要使用的框架. 1.关键技术: AirDrop:实现应用间通信. Text Kit:处理文本和排版. UIKit Dynamics ...

  9. 【BZOJ】【3759】Hungergame饥饿游戏

    博弈论/高斯消元 如果没有打开箱子这个操作,那么就是一个很裸的Nim游戏…… 但是有了打开箱子这个操作,就变得蛋疼了T_T 首先我们可以想到一种直接的做法:打开所有箱子,当然如果此时所有a[i]的xo ...

  10. gcd,lcm,ext_gcd,inv

    Least Common Multiple http://acm.hdu.edu.cn/showproblem.php?pid=1019 #include<cstdio> int gcd( ...