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, 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
HashMapas there would be overhead in the synchronization thatHashtableprovides - I would imagine that
HashMapis more standard, and is used more often. The synchronizedHashtablehas 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
Hashtableis synchronized on the table while access to theHashMapisn't. You can add it, but it isn't there by default.a
HashMapiterator is fail-safe while the enumerator for theHashtableisn't.a
HashMappermits null values in it, whileHashtabledoesn'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.
加载中,请稍侯......
精彩评论