import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashTableHashMap
{
public static void main(String[] args) {
Map map = new HashMap();
map.put("a",null);
map.put("b","B");
map.put(null,"D");
System.out.println(map);
Hashtable ht = new Hashtable();
Set set = map.entrySet();
Iterator itr = set.iterator();
while(itr.hasNext()){
Map.Entry entry = (Map.Entry)itr.next();
Object key = entry.getKey();
Object val = entry.getValue();
if(key==null){
key = ""+null; // Or whatever you want
}
if(val==null){
val = ""+null; // Or whatever you want
}
ht.put(key,val);
}
System.out.println(ht);
}
}
Thursday, January 22, 2009
Convert HashMap to HashTable
How will you convert a HashMap having null values and/or keys to a hash table ?
Subscribe to:
Post Comments (Atom)
6 comments:
How about using the putAll(Map) method of a Hashtable
ht.putAll(map);
that would work fine :)
hi anurag thanks for the info
I will ty this one out and post it accordingly
You can just instantiate a Hashtabe by passing it a Hashmap, thus:
HashMap map = new HashMap();
Hashtable ht = new Hashtable(map);
try doing that ...
tell me whats the result u get ...
u r in for a surprise !!
Nice tip. putAll(map) seems better to me.
Thanks
difference between hashtable and hashmap
PutAll will give you a NPE
public static void testThree() {
Map map = new HashMap();
Hashtable ht = new Hashtable();
map.put("a",null);
map.put("b","B");
map.put(null,"D");
ht.putAll(map);
System.out.println(ht);
}
Post a Comment