HashMap之遍历
HashMap的遍历主要有两种方式:
第一种采用的是foreach模式
,适用于不需要修改HashMap内元素的遍历,只需要获取元素的键/值的情况。
HashMap<K, V> myHashMap;
for (Map.entry<K, V> item : myHashMap.entrySet()){
K key = item.getKey();
V val = item.getValue();
//todo with key and val
//WARNING: DO NOT CHANGE key AND val IF YOU WANT TO REMOVE ITEMS LATER
}
第二种采用迭代器遍历
,不仅适用于HashMap,对其它类型的容器同样适用。
采用这种方法的遍历,可以用下文提及的方式安全地对HashMap内的元素进行修改,并不会对后续的删除操作造成影响。
for (Iterator<Map.entry<K, V>> it = myHashMap.entrySet().iterator; it.hasNext();){
Map.Entry<K, V> item = it.next();
K key = item.getKey();
V val = item.getValue();
//todo with key and val
//you may remove this item using "it.remove();"
}
HashMap之删除元素
如果采用第一种的遍历方法删除HashMap中的元素,Java很有可能会在运行时抛出异常。
HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("1", 1);
myHashMap.put("2", 2);
for (Map.Entry<String, Integer> item : myHashMap.entrySet()){
myHashMap.remove(item.getKey());
}
for (Map.Entry<String, Integer> item : myHashMap.entrySet()){
System.out.println(item.getKey());
}
运行上面的代码,Java抛出了java.util.ConcurrentModificationException
的异常。并附有如下信息。
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
at java.util.HashMap$EntryIterator.next(HashMap.java:1476)
at java.util.HashMap$EntryIterator.next(HashMap.java:1474)
at TestHashmap.main(TestHashmap.java:14)
hashMap的中有一个域modCount
,每次对集合进行修改(增添元素,删除元素……)时都会modCount++
迭代HashMap的HashIterator中有一个变量expectedModCount,该变量会初始化和modCount相等,但如果接下来如果集合进行修改modCount改变,就会造成expectedModCount!=modCount,此时就会抛出java.util.ConcurrentModificationException异常
过程类似下图(与ArrayList类似)
所以,我们改用第二种遍历方式。
代码如下:
for (Iterator<Map.Entry<String, Integer>> it = myHashMap.entrySet().iterator(); it.hasNext();){
Map.Entry<String, Integer> item = it.next();
//... todo with item
it.remove();
}
for (Map.Entry<String, Integer> item : myHashMap.entrySet()){
System.out.println(item.getKey());
}
参考:https://blog.csdn.net/tttzzztttzzz/article/details/87556048