When should I use a Hashtable versus a HashMap
Never.
Hashtable
was the original implementation of a map in Java 1. It's been overtaken by the Map<K,V>
implementations defined in the Java Collections Framework. Sure, Hashtable
has been retrofitted to implement Map
but that's not terribly useful.
It has the main problem in that it's synchronized. This means that it will be slow in any circumstance where it is shared between threads. ConcurrentHashMap
is a better choice in that situation. If you are running on a single thread then the un-synchronized HashMap
is a better choice.
This is not a question about the differences between
Hashtable
andHashMap
Well it is really...
I'm wondering about the scenarios where it would be more appropriate to use a
Hashtable
instead of aHashMap
.
Precisely when you want the differences between the two:
- When you want to run on Java 1.1
- When you want each operation to be synchronized (getting you a form of thread safety, so long as you never iterate over it) - and for some reason don't want to use
Collections.synchronizedMap
over aHashMap
- When you don't want to be able to store null values
- When the memory difference is actually significant (only after you've proved this is the case) - I wasn't even aware of this difference, personally...
- When you're forced to by a nasty API which returns or takes
Hashtable
(relatively rare, fortunately)
I can't remember the last time I was in that situation, personally - I would say it's vanishingly rare to be appropriate to use Hashtable
in modern Java code.