and - hashtable java




Differences between HashMap and Hashtable? (20)

1)Hashtable is synchronized whereas hashmap is not. 2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

3)HashMap permits null values in it, while Hashtable doesn't.

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

Which is more efficient for non-threaded applications?


1.Hashmap and HashTable both store key and value.

2.Hashmap can store one key as null. Hashtable can't store null.

3.HashMap is not synchronized but Hashtable is synchronized.

4.HashMap can be synchronized with Collection.SyncronizedMap(map)

Map hashmap = new HashMap();

Map map = Collections.SyncronizedMap(hashmap);

HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.

Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.


HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.


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.


Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.


Hashtable:

Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.

Example :

import java.util.Map;
import java.util.Hashtable;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states= new Hashtable<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    //will throw NullPointerEcxeption at runtime

    System.out.println(states.get(1));
    System.out.println(states.get(2));
//  System.out.println(states.get(3));

    }
}

HashMap:

HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.

Example:

import java.util.HashMap;
import java.util.Map;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states = new HashMap<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    // Okay
    states.put(null,"UK");

    System.out.println(states.get(1));
    System.out.println(states.get(2));
    System.out.println(states.get(3));

    }
}

HashMap and HashTable

  • Some important points about HashMap and HashTable. please read below details.

1) Hashtable and Hashmap implement the java.util.Map interface 2) Both Hashmap and Hashtable is the hash based collection. and working on hashing. so these are similarity of HashMap and HashTable.

  • What is the difference between HashMap and HashTable?

1) First difference is HashMap is not thread safe While HashTable is ThreadSafe
2) HashMap is performance wise better because it is not thread safe. while Hashtable performance wise is not better because it is thread safe. so multiple thread can not access Hashtable at the same time.


Another key difference between hashtable and hashmap is that Iterator in the HashMap is fail-fast 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."

My source: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html


Apart from the differences already mentioned, it should be noted that since Java 8, HashMap dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is

O(log(n)) for HashMap Vs O(n) in Hashtable.

*The aforementioned improvement has not been applied to Hashtable yet, but only to HashMap, LinkedHashMap, and ConcurrentHashMap.

FYI, currently,

  • TREEIFY_THRESHOLD = 8 : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.
  • UNTREEIFY_THRESHOLD = 6 : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.

Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.

For example, compare Java 5 Map iterating:

for (Elem elem : map.keys()) {
  elem.doSth();
}

versus the old Hashtable approach:

for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
  Elem elem = (Elem) en.nextElement();
  elem.doSth();
}

In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:

Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
map["apples"];

Update: No, they won't land in 1.8... :(

Are Project Coin's collection enhancements going to be in JDK8?


For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.


HashMaps gives you freedom of synchronization and debugging is lot more easier


Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.

For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.


Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.

Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.

Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.


My small contribution :

  1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.

  2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.

  3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.


Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.

Java Collection Matrix


There are 5 basic differentiations with HashTable and HashMaps.

  1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.
  2. In Hashtable there is a function contains(), which is very confusing to use. Because the meaning of contains is slightly deviating. Whether it means contains key or contains value? tough to understand. Same thing in Maps we have ContainsKey() and ContainsValue() functions, which are very easy to understand.
  3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.
  4. HashTables are by default synchronized, so it can be used with multiple threads easily. Where as HashMaps are not synchronized by default, so can be used with only single thread. But you can still convert HashMap to synchronized by using Collections util class's synchronizedMap(Map m) function.
  5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.

There is many good answer already posted. I'm adding few new points and summarizing it.

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.

HashMap

  1. HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
  2. HashMap allows one null key and multiple null values.
  3. HashMap is a new class introduced in JDK 1.2.
  4. HashMap is fast.
  5. We can make the HashMap as synchronized by calling this code
    Map m = Collections.synchronizedMap(HashMap);
  6. HashMap is traversed by Iterator.
  7. Iterator in HashMap is fail-fast.
  8. HashMap inherits AbstractMap class.

Hashtable

  1. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  2. Hashtable doesn't allow any null key or value.
  3. Hashtable is a legacy class.
  4. Hashtable is slow.
  5. Hashtable is internally synchronized and can't be unsynchronized.
  6. Hashtable is traversed by Enumerator and Iterator.
  7. Enumerator in Hashtable is not fail-fast.
  8. Hashtable inherits Dictionary class.

Further reading What is difference between HashMap and Hashtable in Java?


This question is often asked in interview to check whether candidate understands 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 of 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 lock to be released.
  2. Fail-safe is relevant from 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 "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 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





hashtable