Reputation: 95488
This is not a question about the differences between I understand that a Hashtable
and HashMap
.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
.
Upvotes: 28
Views: 27809
Reputation: 403441
InitialContext
in JNDII can think of only one valid reason - when you're using an API that requires it, such as JNDI’s hugely irritating InitialContext
class.
Other than that, I can see no good reason to use Hashtable
at all. You can get a synchronized version of HashMap
by using Collections.synchronizedMap
, or use a ConcurrentMap
implementation such as ConcurrentHashMap
or ConcurrentSkipListMap
Upvotes: 8
Reputation: 2366
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.
Upvotes: 19
Reputation: 1499800
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:
Collections.synchronizedMap
over a HashMap
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.
Upvotes: 32
Reputation: 1252
Knowing when to use one class or structure over another is essentially understanding the differences between the two, and deciding which one best suits the problem at hand based on those differences.
I understand that a Hashtable object cannot accept null values
So in the situation where you need to store null values, a Hashtable
would not be appropriate.
Also, in a Hashtable
, enumeration is not fail-safe. So if you need to be able to change the content of the structure while enumerating, a Hashtable
would be more appropriate.
Upvotes: 1
Reputation: 38122
I only see Hashtables in legacy apps/ libraries.
If you can, use ConcurrentHashMap or Collections.synchronizedMap if you need a synchronized Map.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html
Upvotes: 3