且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从哈希图中删除元素时发生java.util.ConcurrentModificationException

更新时间:2021-08-25 23:59:24

您的for循环获取map.entrySet并在其上使用迭代器浏览地图条目(此for循环版本需要Iterable,它从Iterable获取迭代器).当您在地图上使用迭代器,但不使用该迭代器将其从地图中删除时,会收到ConcurrentModificationException.那是地图告诉迭代器它已经过时了.

Your for-loop gets the map.entrySet and uses the iterator on it to work through the map entries (this version of the for-loop requires an Iterable, it gets the iterator from the Iterable). When you are using an iterator on a map, but remove things from the map without using that iterator, you get the ConcurrentModificationException. That is the map telling the iterator that it's out of date.

您可以使用迭代器显式编写一个for循环,如下所示:

You can write a for loop using the iterator explicitly, like this:

for (Iterator<Map.Entry<String, Integer> it = map.entrySet().iterator();
it.hasNext();) {

并在需要删除条目时使用迭代器的remove方法.

and use the iterator's remove method when you need to delete an entry.