difference between linkedhashmap, hashmap, map, hashtable

前端 未结 3 2004
借酒劲吻你
借酒劲吻你 2021-02-04 22:55

I am preparing for software interviews and i am stuck with a question for days now.

I have not been able to figure out the difference between linkedhashmap, map, hashtab

3条回答
  •  走了就别回头了
    2021-02-04 23:10

    I doubt the differences can be explained significantly better than what's already written in the JavaDocs for these classes:

    • Map is the basic interface common to all these classes
    • a Hashtable is one implementation of that interface, for the "old" days when it was thought that having everything synchronized is a good idea (ref. Vector). It offers "kind of" thread-safety, if you know what you are doing. If you are serious about a map which can be used from multiple threads you should absolutely check out the ConcurrentHashMap and ConcurrentSkipListMap.
    • a HashMap is almost the same as a Hashtable, but with the synchronization removed. It's the preferred general-purpose Map implementation.
    • a LinkedHashMap additionally maintains a linked list of it's entries, which allows to maintain an ordering or use it as a LRU cache easily, just read the JavaDoc.

    All of the aforementioned Map implementations have their basic get/put operations in (amortized) O(1) time complexity. There are minor differences in the handling of null values, it's inevitable to check the JavaDoc for details.

    To get an idea of how these classes are implemeted, have a look at their inheritance tree:

    • Map (just the interface)
      • Dictionary (obsoleted abstract class)
        • Hashtable (the "old" map implementation lives on it's own)
      • AbstractMap (the basic functionality of the "new" map implementations)
        • HashMap (the first concrete map implementation for general purpose use)
          • LinkedHashMap (extends HashMap by mainaining the linked list)

提交回复
热议问题