I want to remove key from hash Table without using the remove function. so give me some idea.
- 
                    13And why would you want to do that? – Peter Lang Jul 15 '10 at 11:58
- 
                    4what's wrong with the `remove()` _method_? – Bozho Jul 15 '10 at 12:01
- 
                    1Maybe Datta wants to remove entries while iterating through the entryset. And remove throws ugly exceptions. – Andreas Dolk Jul 15 '10 at 12:13
- 
                    why would you ever do this, except for homework? – hvgotcodes Jul 15 '10 at 12:17
2 Answers
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
 
    
    - 1
- 1
 
    
    - 376,812
- 128
- 561
- 623
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).
 
    
    - 202,709
- 46
- 318
- 350
