map的三种遍历方式

来源:互联网 发布:asp.net与php 编辑:程序博客网 时间:2024/06/06 03:03

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这种情况