在Java中迭代和删除Hashtable [英] Iterating over and deleting from Hashtable in Java
本文介绍了在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循环语法。以下示例遍历 Map
的 Integer
, String
pair,删除 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文