更新时间:2023-07-05 来源:黑马程序员 浏览量:

在使用HashMap进行遍历和删除操作时,不能在遍历过程中直接删除元素,这是因为HashMap的迭代器设计不支持在遍历时对集合进行结构性修改。当在遍历过程中直接删除元素时,会导致迭代器的状态与实际集合的状态不一致,可能引发ConcurrentModificationException(并发修改异常)。
具体来说,当创建HashMap的迭代器时,会生成一个"modCount"字段,表示HashMap结构性修改的次数。每当对HashMap进行插入、删除等操作时,"modCount"都会增加。而在迭代器遍历HashMap时,会将当前的"modCount"与之前保存的"expectedModCount"进行比较,如果两者不相等,则会抛出ConcurrentModificationException。
下面我们看一个简单的代码示例,演示了在遍历HashMap过程中删除元素可能导致的异常:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
Iterator<Integer> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
if (key == 2) {
hashMap.remove(key); // 在遍历过程中直接删除元素
}
}
}
}在上述代码中,尝试在遍历HashMap时删除元素,当删除key为2的元素时,会抛出ConcurrentModificationException异常。
为了避免这种异常,可以通过使用迭代器的remove()方法进行安全的删除操作。下面是修改后的代码示例:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
Iterator<Integer> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
if (key == 2) {
iterator.remove(); // 使用迭代器的remove()方法删除元素
}
}
}
}在修改后的代码中,使用了迭代器的remove()方法进行删除操作,这样可以避免ConcurrentModificationException异常的发生。
1024首播|39岁程序员逆袭记:不被年龄定义,AI浪潮里再迎春天
2025-10-241024程序员节丨10年同行,致敬用代码改变世界的你
2025-10-24【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19