java遍历map并删除元素时,使用不当会抛弃异常

原文:http://blog.sina.com.cn/s/blog_62c8f3c90101bya2.html

在遍历是不能用map.remove(key),而是用keys.remove().看下面转载
http://www.3lian.com/edu/2012/12-15/49507.html
* 会引发 并发修改异常,可以通过迭代器的remove(): * 从迭代器指向的 collection 中移除当前迭代元素 * 来达到删除访问中的元素的目的。 * */ 
public static void main(String[] args) { 
map.put(1,"one"); 
map.put(2,"two"); 
map.put(3,"three"); 
map.put(4,"four"); 
map.put(5,"five"); 
map.put(6,"six"); 
map.put(7,"seven"); 
map.put(8,"eight"); 
map.put(5,"five"); 
map.put(9,"nine"); 
map.put(10,"ten"); 
Iterator> it = map.entrySet().iterator(); 
while(it.hasNext()){ 
Map.Entry entry=it.next(); 
int key=entry.getKey(); 
if(key%2==1){ 
System.out.println("delete this: "+key+" = "+key); 
//map.put(key, "奇数"); //ConcurrentModificationException 
//map.remove(key); //ConcurrentModificationException 
it.remove(); //OK 
} 
} 
//遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。 
System.out.println("-------nt最终的map的元素遍历:"); 
for(Map.Entry entry:map.entrySet()){ 
int k=entry.getKey(); 
String v=entry.getValue(); 
System.out.println(k+" = "+v); 
} 
} 
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值