遍历并remove HashMap中的元素时,遇到ConcurrentModificationException
遍历并remove HashMap中的元素时,遇到ConcurrentModificationException
- ImageView key = peer.getKey();
- key.setImageBitmap(peer.getValue().getProfile_image());
- mPortraitViewPeers.remove(key);
- }
for (Map.Entry<ImageView, UserConcise> peer : mPortraitViewPeers.entrySet()) {
ImageView key = peer.getKey();
key.setImageBitmap(peer.getValue().getProfile_image());
mPortraitViewPeers.remove(key);
}
在查看一些资料后,修改的代码
- 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();
- }
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();
}
以下是网上的解释
- java.util.ConcurrentModificationException
- 工作中碰到个ConcurrentModificationException。代码如下:
- List list = ...;
- for(Iterator iter = list.iterator(); iter.hasNext();) {
- Object obj = iter.next();
- ...
- if(***) {
- list.remove(obj);
- }
- }
- 在执行了remove方法之后,再去执行循环,iter.next()的时候,报java.util.ConcurrentModificationException(当然,如果remove的是最后一条,就不会再去执行next()操作了)
- 下面来看一下源码
- public interface Iterator<E> {
- boolean hasNext();
- E next();
- void remove();
- }
- public interface Collection<E> extends Iterable<E> {
- ...
- Iterator<E> iterator();
- boolean add(E o);
- boolean remove(Object o);
- ...
- }
- 这里有两个remove方法
- 接下来来看看AbstractList
- public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
- //AbstractCollection和List都继承了Collection
- protected transient int modCount = 0;
- private class Itr implements Iterator<E> { //内部类Itr
- int cursor = 0;
- int lastRet = -1;
- int expectedModCount = modCount;
- public boolean hasNext() {
- return cursor != size();
- }
- public E next() {
- checkForComodification(); //特别注意这个方法
- try {
- E next = get(cursor);
- lastRet = cursor++;
- return next;
- } catch(IndexOutOfBoundsException e) {
- checkForComodification();
- throw new NoSuchElementException();
- }
- }
- public void remove() {
- if (lastRet == -1)
- throw new IllegalStateException();
- checkForComodification();
- try {
- AbstractList.this.remove(lastRet); //执行remove对象的操作
- if (lastRet < cursor)
- cursor--;
- lastRet = -1;
- expectedModCount = modCount; //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
- } catch(IndexOutOfBoundsException e) {
- throw new ConcurrentModificationException();
- }
- }
- final void checkForComodification() {
- if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
- throw new ConcurrentModificationException();
- }
- }
- }
- remove(Object o)在ArrayList中实现如下:
- public boolean remove(Object o) {
- if (o == null) {
- for (int index = 0; index < size; index++)
- if (elementData[index] == null) {
- fastRemove(index);
- return true;
- }
- } else {
- for (int index = 0; index < size; index++)
- if (o.equals(elementData[index])) {
- fastRemove(index);
- return true;
- }
- }
- return false;
- }
- private void fastRemove(int index) {
- modCount++; //只增加了modCount
- ....
- }
- 所以,产生ConcurrentModificationException的原因就是:
- 执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
- 要避免这个Exception,就应该使用remove()方法。
- 这里我们就不看add(Object o)方法了,也是同样的原因,但没有对应的add()方法。一般嘛,就另建一个List了
- 下面是网上的其他解释,更能从本质上解释原因:
- Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
- 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
遍历并remove HashMap中的元素时,遇到ConcurrentModificationException的更多相关文章
- list,set等集合遍历时,不能remove集合中的元素。需要new一个Object或者list,set,里面add需要删除的元素,等集合遍历完了进行remove(Object)或者removeAll(list/set)操作
list,set等集合遍历时,不能remove集合中的元素.需要new一个Object或者list,set,里面add需要删除的元素,等集合遍历完了进行remove(Object)或者removeAl ...
- 修改NSMutableArray中的元素时的注意事项
最近做项目遇到从文件加载数组,并对数组中的元素进行操作的问题,特意写了个Demo,记录下要注意的东西: 代码如下: NSArray *array = @["]; NSMutableArray ...
- Java 循环遍历删除set list中的元素
删除List和Set中的某些元素 错误代码的写法: Set<String> set = new HashSet<String>(); set.add("aaaaaa& ...
- 整理悬浮在列表中a元素时改变a元素上下边框颜色的问题。
整理一下当悬浮在a元素上时a的上下边颜色改变,并且里面的内容不会移动,下面是PSD图效果区域: 刚开始我先给A元素加了上下边框和颜色,利用a:hover改变a元素上下的边框颜色,但是第一个a元素的下边 ...
- 遍历std::list过程中删除元素后继续遍历过程
std::list::erase Erase elements Removes from the list container either a single element (position) o ...
- C#实现在foreach遍历中删除集合中的元素(方法总结)
目录 方法一:采用for循环,并且从尾到头遍历 方法二:使用递归 方法三:通过泛型类实现IEnumerator 在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致 ...
- [改善Java代码]减少HashMap中元素的数量
在系统开发中我们经常会使用HashMap作为数据集容器,或者是用缓冲池来处理,一般很稳定,但偶尔也会出现内存溢出的问题(OutOfMemory错误),而且这经常是与HashMap有关的.而且这经常是与 ...
- 当JAVA集合移除自身集合元素时发生的诸多问题
一段代码目的是想删除集合中包括"a"字符串的集合项: public class TestForeach { public static void main(String[] arg ...
- 【java基础 12】HashMap中是如何形成环形链表的?
导读:经过前面的博客总结,可以知道的是,HashMap是有一个一维数组和一个链表组成,从而得知,在解决冲突问题时,hashmap选择的是链地址法.为什么HashMap会用一个数组这链表组成,当时给出的 ...
随机推荐
- Tools for Presention
ZoomIt v4.5 http://technet.microsoft.com/en-us/sysinternals/bb897434.aspx 微软的教师演示工具 主要有放大,画图,倒计时的功能. ...
- System V消息队列
消息的基本属性 System V的消息属性包含在一个msqid_ds的结构中 struct msqid_ds{ struct ipc_cerm msg_perm; //读取权限, 0644, 0777 ...
- 第三章 DispatcherServlet详解
3.1.DispatcherServlet作用 DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派,而且与Spring Io ...
- 在Visual Studio中快速启动调试Web应用程序
原文:http://blog.csdn.net/effun/article/details/2638535 到2005,Visual Studio在启动调试的功能上进行了一些改善,不过因为只是简单的一 ...
- 如何在Eclipse中配置Tomcat服务器
之前使用MyEclipse来开发Web应用,可以在MyEclipse中配置服务器,配置完后,直接运行服务器即可,很方便. 最近切换到Eclipse开发环境,发现使用Tomcat的方式不太一样,因此在此 ...
- css的transition 属性
把鼠标指针放到 div 元素上,其宽度会从 100px 逐渐变为 300px: div { width:100px; transition: width 2s; -moz-transition: wi ...
- 01-05-01-2【Nhibernate (版本3.3.1.4000) 出入江湖】立即加载实现--NHibernateUtil.Initialize()和添加fetch关键字的HQL查询
相关资料: http://www.cnblogs.com/lyj/archive/2008/10/29/1322373.html 问题的提出: 1.延迟加载,可能会引起session已经关闭的异常,例 ...
- WPF 显示初始化界面
今天在看<WPF编程宝典>时,看到了Application类,该类可以做很多事情,我认为比较实用的是显示初始化界面,因为之前有个项目在打开的时候要加载好多dll,非常耗时,让客户等的蛋疼, ...
- PHP中$_SERVER获取当前页面的完整URL地址
PHP中$_SERVER获取当前页面的完整URL地址,其实很简单,主要是通过$_SERVER超全局变量来实现的. 具体PHP中$_SERVER获取当前页面的完整URL地址如下. #测试网址: ...
- oracle 表空间 用户
Oracle创建表空间.创建用户以及授权.查看权限 创建临时表空间 CREATE TEMPORARY TABLESPACE test_temp TEMPFILE 'C:\oracle\product\ ...