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

后端 未结 30 2420
青春惊慌失措
青春惊慌失措 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 14:08

    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.

提交回复
热议问题