Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between a HashMap and a Hashtable in Java?

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

like image 664
dmanxiii Avatar asked Sep 02 '08 20:09

dmanxiii


People also ask

What is the difference between HashMap and Hashtable data structure?

In general, you should use a HashMap. While both classes use keys to look up values, there are some important differences, including: A HashTable doesn't allow null keys or values; a HashMap does. A HashTable is synchronized to prevent multiple threads from accessing it at once; a HashMap isn't.

What is the difference between Hashtable and HashMap and HashSet in Java?

Hashtable and HashMap both implement Map , HashSet implements Set , and they all use hash codes for keys/objects contained in the sets to improve performance. Hashtable is a legacy class that almost always should be avoided in favor of HashMap .

Should I use HashMap or Hashtable Java?

When to use HashMap and Hashtable? HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications . We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 .


4 Answers

There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

like image 178
Josh Brown Avatar answered Oct 13 '22 13:10

Josh Brown


Note, that a lot of the answers state that Hashtable is synchronized. In practice this buys you very little. The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization.

A very common idiom is to "check then put" — i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.

An equivalently synchronised HashMap can be obtained by:

Collections.synchronizedMap(myMap);

But to correctly implement this logic you need additional synchronisation of the form:

synchronized(myMap) {
    if (!myMap.containsKey("tomato"))
        myMap.put("tomato", "red");
}

Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread-safe unless you also guard the Map against being modified through additional synchronization.

Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:

ConcurrentMap.putIfAbsent(key, value);
like image 31
serg10 Avatar answered Oct 13 '22 12:10

serg10


Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.

like image 37
aberrant80 Avatar answered Oct 13 '22 13:10

aberrant80


This question is often asked in interviews to check whether the candidate understands the correct usage of collection classes and is aware of alternative solutions available.

  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms:

  1. Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
  2. Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke the set method since it doesn't modify the collection "structurally". However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of the map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.

The Map Interface

like image 41
sravan Avatar answered Oct 13 '22 12:10

sravan