Reputation: 82993
I've used hash tables occasionally in a couple of languages, but I just came across the Java map while browsing through some code. I checked up the differences in this SO question, which expressed it very clearly. My question is this:
When either one could work for you , which is better to use? Which one should you choose if you're not dealing with nulls/threads...?
Which one is used more often / is more standard?
Upvotes: 3
Views: 404
Reputation: 18888
Hashtable is older. It was shipped already in JDK 1.0. In 1.2, when the collections framework was introduced, Hashtable was identified as a problem since it was implemented with all public methods being synchronized. This was a precaution which is only necessary in multi-threaded contexts and hurts performance otherwise (some people have indicated that this could be optimized away, but YMMV).
Unfortunately it was not possible to just remove the synchronization, since some code already relied on Hashtable being implemented this way. Hence, HashMap was born. While they were at it, they threw in the 'permit nulls' feature and adapted it to the general collections framework.
The same thing happened with StringBuffer which new unsynchronized version is called StringBuilder.
So, in short: Use HashMap: it's the newest and most thought through implementation. Hashtable is legacy. If you want a synchronized implementation you can go for Hashtable or Collections.synchronizedMap(Map).
Upvotes: 5
Reputation: 77995
Hashtable
is one of the original collection classes in Java, while HashMap
is part of the Collections Framework added with Java 2. The main differences are:
access to the Hashtable
is synchronized on the table while access to the HashMap
isn't. You can add it, but it isn't there by default.
a HashMap
iterator is fail-safe while the enumerator for the Hashtable
isn't.
a HashMap
permits null values in it, while Hashtable
doesn't.
So you'd go with HashMap
for any new code. If you need synchronization you're better off with Collections.synchronizedMap(HashMap)
. See this similar SO thread for more ideas.
Upvotes: 0
Reputation: 8446
For general use choose HashMap
because Hashtable
is synchronized, and therefore consumes more computing resources.
Upvotes: 1
Reputation: 41077
HashMap
for local variables or method parameters because they are thread safe.
Upvotes: -2
Reputation: 39475
HashMap
as there would be overhead in the synchronization that Hashtable
providesHashMap
is more standard, and is used more often. The synchronized Hashtable
has to a certain extent been superseded by advances in Collections and concurrency frameworks. Upvotes: 7