外出旅行、冬季保暖得常备户外袜、速干袜、加厚袜子哦。

猛戳乐途驿站http://zhoupa1188.taobao.com抢购品牌男女式加厚户外袜子,coolmax、全棉、保暖、吸汗、速干、登山、徒步袜子。满10包邮


谢炜的cnblogs

CSDN上比较完整:http://hi.csdn.net/xiefeifeihu

导航

遍历集合时删除元素,抛出java.util.ConcurrentModificationException的解决办法

遍历集合删除其中的元素时可能会抛出java.util.ConcurrentModificationException异常。

下面的代码就会抛出异常:

1:  for (String s : map.keySet()) {
2:      if ("val".equals(s))
3:          map.remove(s);
4:  }

 

怎么解决这个问题呢?用迭代器:

1:  Iterator it = map.keySet().iterator();
2:  while (it.hasNext()) {
3:      String obj = it.next();
4:      if ("2".equals(obj)) {
5:          it.remove();
6:      }
7:  }

调用迭代器的remove方法可以安全的删除元素:it.remove();

如果用集合的remove方法:map.remove(s); 就会报java.util.ConcurrentModificationException异常:

1:  Iterator it = map.keySet().iterator();
2:  while (it.hasNext()) {
3:      String obj = it.next();
4:      if ("2".equals(obj)) {
5:          // it.remove();
6:          map.remove(obj);
7:      }
8:  }

posted on 2009-11-30 17:36  飞飞狐  阅读(1553)  评论(0编辑  收藏  举报

外出旅行、冬季保暖得常备户外袜、速干袜、加厚袜子哦。

猛戳乐途驿站http://zhoupa1188.taobao.com抢购品牌男女式加厚户外袜子,coolmax、全棉、保暖、吸汗、速干、登山、徒步袜子。满10包邮