本文介紹了Java中的Hashtable迭代和刪除的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在 Java 中有一個 Hashtable,想要遍歷表中的所有值并在迭代時刪除特定的鍵值對.
I have a Hashtable in Java and want to iterate over all the values in the table and delete a particular key-value pair while iterating.
如何做到這一點?
推薦答案
您需要使用顯式 java.util.Iterator
來迭代 Map
的條目設置而不是能夠使用 Java 6 中可用的增強的 For 循環語法.以下示例遍歷 Integer
、String
的 Map
對,刪除 Integer
鍵為 null 或等于 0 的任何條目.
You need to use an explicit java.util.Iterator
to iterate over the Map
's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map
of Integer
, String
pairs, removing any entry whose Integer
key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
這篇關于Java中的Hashtable迭代和刪除的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!