您的位置:首页 > 其它

map的三种遍历方式

2017-09-24 08:15 232 查看
map的三种遍历方式

Map<String, String>map = new HashMap<>();
map.put("a","aa");
map.put("b","bb");
map.put("c","cc");
map.put("d","dd");

//第一种
for (String key: map.keySet()){
System.out.println("key: "+ key+" value: "+ map.get(key));
}

//第二种
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
String key = iterator.next().getKey();
// map.remove(key); 会抛出ConcurrentModificationException异常
//但是如果使用iterator.remove()方法就不会报错
System.out.println("key: "+ key+" value: "+ map.get(key));
}

//第三种
for (Map.Entry<String, String>entry: map.entrySet()){
String key = entry.getKey();
// map.remove(key); 会抛出ConcurrentModificationException异常
System.out.println("key: "+ key+" value: "+ map.get(key));
}


但是对于
collection
类遍历企图修改或者是删除某个元素的时候,会报
ConcurrentModificationException
的错误,无论是使用iterator还是使用map.entrySet方式:


java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
at com.sxz.zxd.java.StringTest.mapTest(StringTest.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)


即java集合(Collection)中采用fail-fast机制。当某一个线程A通过iterator去遍历某集合C的过程中,若该集合的内容被其他线程所改变了,当线程A继续访问集合C时,抛出ConcurrentModificationException异常,出现fail-fast这种情况
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: