22

Possible Duplicate:
Differences between HashMap and Hashtable?

I've seen hash tables and hash maps used in different code but they look like they do the same thing. Is there a difference between them? Which one should I use in my code?

Community
  • 1
  • 1
user1813746
  • 255
  • 1
  • 4
  • Yep, the primary difference is that Hashtable is synchronized, and HashMap is not. They also have different superclass hierarchies. (FWIW, I've on a couple of occasions seen fairly severe failures in large commercial apps due to using HashMap in a concurrent environment.) – Hot Licks Nov 10 '12 at 01:00
  • BTW, it's "HashMap" and "Hashtable". Note the capitalization. – Hot Licks Nov 10 '12 at 01:01
  • 2
    Did you consider reading the Javadoc? – user207421 Nov 10 '12 at 01:08
  • @HotLicks - *"I've on a couple of occasions seen fairly severe failures in large commercial apps due to using HashMap in a concurrent environment."* - but using a `Hashtable` might be a bad idea too due to contention issues. Concurrent applications require more sophisticated thinking ... if you want them to scale. – Stephen C Nov 10 '12 at 01:27
  • `Hashtable` is more or less deprecated; `ConcurrentHashMap` is designed to work in a concurrent environment, but is much better at it. – Louis Wasserman Nov 10 '12 at 02:13
  • @StephenC -- In these cases there was very little contention ... had there been contention the bugs would have been found in testing rather than in the field. And when a HashMap is updated concurrently the results aren't pretty. – Hot Licks Nov 10 '12 at 02:43

3 Answers3

11

java.util.Hashtable methods are synchronized , java.util.Hashmap methods are not. If you use Hashtable there will be a performance hit as no two threads will be able to access its methods at the same time. If you care about Thread safety in your app Hashtable is the way to go. if you dont care about thread safety Hashmap is the way to go as it is mor eefficient then hashtable. also java.util.Hashtable doesnt allow any null keys, where as java.util.HashMap allows one null key.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
4

Hashtable is synchronized, where as HashMap is not. This means if you only have a single thread accessing the data, use a HashMap, otherwise use a Hashtable.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
1

HashTable dont't allow null keys where as hashmap allows one null key

Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62