remove key from hash table
I want to remove key from hash Table without using the remove function. s开发者_如何学JAVAo give me some idea.
You can emulate removed keys by supplementing a Map<K,V> map
with a Set<K> removedKeys
.
To remove a key
, just removedKeys.add(key);
.
Whenever a K key
is queried, you see if removedKeys.contains(key)
. If it does, then key
has effectively been "removed" from map
.
Note that this is a very peculiar way of doing things, and keeping the two structures in sync may cause later headaches. It's more acceptable if removedKeys
is localized and short-lived, e.g. when you're iterating over the entries of a Map
using for-each
and want to remove some keys later, while avoiding ConcurrentModificationException
.
So you may have something like this:
static void removeEvenKeys(Map<Integer,String> map) {
Set<Integer> removedKeys = new HashSet<Integer>();
for (Map.Entry<Integer,String> entry : map.entrySet()) {
if (entry.getKey() %2 == 0) {
removedKeys.add(entry.getKey());
}
}
map.keySet().removeAll(removedKeys);
}
And then elsewhere:
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.put(4, "Four");
removeEvenKeys(map);
System.out.println(map);
// "{1=One, 3=Three}"
See also
- Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces
Related questions
- Java hashmap vs hashtable
- Java: Efficient Equivalent to Removing while Iterating a Collection
You can call remove()
on an Iterator
instead of on the Hashtable
itself:
Hashtable<String, String> map = new Hashtable<String, String>();
map.put("one", "een");
map.put("two", "twee");
map.put("three", "drie");
for (Iterator<Map.Entry<String, String>> i = map.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, String> entry = i.next();
if ("two".equals(entry.getKey())) {
// Removes entry from Hashtable; note, this is not the Hashtable.remove() method
// but the Iterator.remove() method
i.remove();
}
}
System.out.println(map);
(NOTE: You should use HashMap
instead of the legacy collection class Hashtable
).
精彩评论