首頁常見問題正文

HashMap為什么不能一邊遍歷一遍刪除?

更新時間:2023-07-05 來源:黑馬程序員 瀏覽量:

IT培訓班

  在使用HashMap進行遍歷和刪除操作時,不能在遍歷過程中直接刪除元素,這是因為HashMap的迭代器設計不支持在遍歷時對集合進行結(jié)構(gòu)性修改。當在遍歷過程中直接刪除元素時,會導致迭代器的狀態(tài)與實際集合的狀態(tài)不一致,可能引發(fā)ConcurrentModificationException(并發(fā)修改異常)。

  具體來說,當創(chuàng)建HashMap的迭代器時,會生成一個"modCount"字段,表示HashMap結(jié)構(gòu)性修改的次數(shù)。每當對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異常的發(fā)生。

分享到:
在線咨詢 我要報名
和我們在線交談!