When should I use a Hashtable versus a HashMap

Vivin Paliath picture Vivin Paliath · Mar 2, 2012 · Viewed 24.8k times · Source

This is not a question about the differences between Hashtable and HashMap. I understand that a Hashtable object cannot accept null values for either key or value entries, that it is synchronized collection, and that it uses slightly less memory than a HashMap.

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

Answer

Jon Skeet picture Jon Skeet · Mar 2, 2012

This is not a question about the differences between Hashtable and HashMap

Well it is really...

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

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 a HashMap
  • 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.