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

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

    • HashTable is synchronized, if you are using it in a single thread you can use HashMap, which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. Youn can wrap a unsynchronized map in a synchronized one using :

      Map m = Collections.synchronizedMap(new HashMap(...));
      
    • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.

    • The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

    • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).

    • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.

    • HashMap doesn't guarantee the order in which elements are returned. For HashTable I guess it's the same but I'm not entirely sure, I don't find ressource that clearly state that.

提交回复
热议问题