Hi, 1) Can any of explain the difference between Hash Map and Hash Table? 2) When to use Hash Map and when to use Hash Table? 3) What are the relative merits and demerits?. Thanks in advance, Narasimha.
Originally posted by narasimha rao bandlamudi: 1) Can any of explain the difference between Hash Map and Hash Table?
The main difference is that HashMap was conceived as part of the Collections framework introduced in version 1.2 of the JDK. Hashtable is a legacy class predating the Collections framework. Further differences are that Hashtable is synchronized, whereas HashMap is not. Also, HashMap can take null keys and values, but Hashtable can't.
2) When to use Hash Map and when to use Hash Table?
IMNSHO, always and never, respectively.
3) What are the relative merits and demerits?
Hashtable has been retrofitted with the Map interface, giving it a bloated and ambiguous API. What shall I use today, elements() or values()?
Hashtable doesn't like null keys or values.
In single-threaded code, the synchronization in Hashtable is useless and will only decrease performance.
In most multi-threaded code, too, the synchronization in Hashtable is useless and will only decrease performance. The operations that need to be atomic (i.e. synchronized) are rarely the little Hashtable methods, but much coarser-grained methods that you write and which use the Map behind the scenes.
The fact that "Hashtable is threadsafe" tends to lure inexperienced developers into writing thread-unsafe code.
The Collections framework is a coherent, consistent, functionally complete set of interfaces and implementations. Hashtable is outside that framework and represents so much redundant baggage. If you really need a synchronized Map (very rare indeed), use Collections.sychronizedMap(new HashMap()).
- Peter [ March 25, 2003: Message edited by: Peter den Haan ]
Narasimha Rao B.
Joined: Aug 26, 2002
Hi Peter, thank you very much for your detailed explanation.