Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use a Hashtable versus a HashMap

This is not a question about the differences between Hashtable and HashMap. I understand that a Hashtable object cannot accept null values for either key or value entries, that it is synchronized collection, and that it uses slightly less memory than a HashMap.

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

like image 692
Vivin Paliath Avatar asked Mar 02 '12 15:03

Vivin Paliath


People also ask

Which is better HashMap or Hashtable?

HashMap is non-syncronized and is not thread safe while HashTable is thread safe and is synchronized. HashMap allows one null key and values can be null whereas HashTable doesn't allow null key or value. HashMap is faster than HashTable. HashMap iterator is fail-safe where HashTable iterator is not fail-safe.

When should we use Hashtable in Java?

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. It is similar to HashMap, but is synchronized.

Which is faster Hashtable or HashMap?

HashMap is not synchronized, therefore it's faster and uses less memory than Hashtable. Generally, unsynchronized objects are faster than synchronized ones in a single threaded application.

When should a HashMap be used?

Using HashMap makes sense only when unique keys are available for the data we want to store. We should use it when searching for items based on a key and quick access time is an important requirement. We should avoid using HashMap when it is important to maintain the same order of items in a collection.


1 Answers

This is not a question about the differences between Hashtable and HashMap

Well it is really...

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

Precisely when you want the differences between the two:

  • When you want to run on Java 1.1
  • When you want each operation to be synchronized (getting you a form of thread safety, so long as you never iterate over it) - and for some reason don't want to use Collections.synchronizedMap over a HashMap
  • When you don't want to be able to store null values
  • When the memory difference is actually significant (only after you've proved this is the case) - I wasn't even aware of this difference, personally...
  • When you're forced to by a nasty API which returns or takes Hashtable (relatively rare, fortunately)

I can't remember the last time I was in that situation, personally - I would say it's vanishingly rare to be appropriate to use Hashtable in modern Java code.

like image 190
Jon Skeet Avatar answered Sep 21 '22 00:09

Jon Skeet