开发者

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

开发者 https://www.devze.com 2022-12-20 11:09 出处:网络
I\'ve used hash tables occasionally in a couple of languages, bu开发者_开发百科t I just came across the Java map while browsing through some code. I checked up the differences in this SO question, whi

I've used hash tables occasionally in a couple of languages, bu开发者_开发百科t 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?


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


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).


HashMap because it runs faster.


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消