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

后端 未结 30 2351
青春惊慌失措
青春惊慌失措 2020-11-21 13:30

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

Which is more efficient for non-threaded applications?

30条回答
  •  有刺的猬
    2020-11-21 13:45

    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?

提交回复
热议问题