Difference between HashMap, LinkedHashMap and TreeMap

后端 未结 17 2150
醉话见心
醉话见心 2020-11-22 01:01

What is the difference between HashMap, LinkedHashMap and TreeMap in Java? I don\'t see any difference in the output as all the three

17条回答
  •  无人及你
    2020-11-22 01:34

    While there are plenty of excellent Answers here, I'd like to present my own table describing the various Map implementations bundled with Java 11.

    We can see these differences listed on the table graphic:

    • HashMap is the general-purpose Map commonly used when you have no special needs.
    • LinkedHashMap extends HashMap, adding this behavior: Maintains an order, the order in which the entries were originally added. Altering the value for key-value entry does not alter its place in the order.
    • TreeMap too maintains an order, but uses either (a) the “natural” order, meaning the value of the compareTo method on the key objects defined on the Comparable interface, or (b) invokes a Comparator implementation you provide.
      • TreeMap implements both the SortedMap interface, and its successor, the NavigableMap interface.
    • NULLs: TreeMap does not allow a NULL as the key, while HashMap & LinkedHashMap do.
      • All three allow NULL as the value.
    • HashTable is legacy, from Java 1. Supplanted by the ConcurrentHashMap class. Quoting the Javadoc: ConcurrentHashMap obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.

提交回复
热议问题