froadie
froadie

Reputation: 82993

For general cases, when either one would work, which is better to use, a hashmap or a hashtable?

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:

Upvotes: 3

Views: 404

Answers (6)

Alexander Torstling
Alexander Torstling

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

JRL
JRL

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

Drew Wills
Drew Wills

Reputation: 8446

For general use choose HashMap because Hashtable is synchronized, and therefore consumes more computing resources.

Upvotes: 1

fastcodejava
fastcodejava

Reputation: 41077

HashMap for local variables or method parameters because they are thread safe.

Upvotes: -2

akf
akf

Reputation: 39475

  • If either would work for you, I would use a HashMap as there would be overhead in the synchronization that Hashtable provides
  • I would imagine that HashMap 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

cherouvim
cherouvim

Reputation: 31903

HashMap because it runs faster.

Upvotes: 1

Related Questions