java map failed_遍历map出现错误java.util.ConcurrentModificationException

一、遍历map的四种方式:

1、使用迭代器:

Map map = new HashMap();

map.put("name","xiaoming");

map.put("age","20");

map.put("sex","male");

Iterator> iterator = map.entrySet().iterator();

while(iterator.hasNext()){

System.out.println(iterator.next());

}

2、for循环遍历键,通过键得到值

for(String k : map.keySet()){

System.out.println(k+":"+map.get(k));

}

3、for循环遍历,得到键值

for(Map.Entry m : map.entrySet()){

System.out.println(m.getKey()+":"+m.getValue());

}

4、for循环遍历 值,无法得到键

for(String v : map.values()){

System.out.println(v);

}

二、map删除指定元素的问题

想要删除map中的键为"age"的元素,试图这样做:

Map map = new HashMap();

map.put("name","xiaoming");

map.put("age","20");

map.put("sex","male");

for(Map.Entry m : map.entrySet()){

if(m.getKey().equals("age")){

map.remove(m.getKey());

}

}

报错:

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)

at java.util.HashMap$EntryIterator.next(HashMap.java:934)

at java.util.HashMap$EntryIterator.next(HashMap.java:932)

at cn.java.test.map.MapTest.main(MapTest.java:22)

原因是:HashMap是线程不安全的。

两种方法解决:

1、使用迭代器的remove方法:

Map map = new HashMap();

map.put("name","xiaoming");

map.put("age","20");

map.put("sex","male");

Iterator> iterator = map.entrySet().iterator();

while(iterator.hasNext()){

Map.Entry m = iterator.next();

if(m.getKey().equals("age")){

System.out.println("将要删除键为:"+m.getKey()+"的元素");

iterator.remove();

}

}

System.out.println("删除后结果为:");

for(Map.Entry m : map.entrySet()){

System.out.println(m.getKey()+"="+m.getValue());

}

2、使用线程安全的 ConcurrentHashMap类:

Map map = new ConcurrentHashMap();

map.put("name","xiaoming");

map.put("age","20");

map.put("sex","male");

for(Map.Entry m : map.entrySet()){

if(m.getKey().equals("age")){

map.remove(m.getKey());

}

}

System.out.println("删除后结果为:");

for(Map.Entry m : map.entrySet()){

System.out.println(m.getKey()+"="+m.getValue());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值