Difference between HashMap, LinkedHashMap and TreeMap

后端 未结 17 2043
醉话见心
醉话见心 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:40

    I prefer visual presentation:

    ╔══════════════╦═════════════════════╦═══════════════════╦═════════════════════╗
    ║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap   ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║ Iteration    ║  no guarantee order ║ sorted according  ║                     ║
    ║   Order      ║ will remain constant║ to the natural    ║    insertion-order  ║
    ║              ║      over time      ║    ordering       ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║  Get/put     ║                     ║                   ║                     ║
    ║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)        ║
    ║ containsKey  ║                     ║                   ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║              ║                     ║   NavigableMap    ║                     ║
    ║  Interfaces  ║         Map         ║       Map         ║         Map         ║
    ║              ║                     ║    SortedMap      ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║              ║                     ║                   ║                     ║
    ║     Null     ║       allowed       ║    only values    ║       allowed       ║
    ║ values/keys  ║                     ║                   ║                     ║
    ╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣
    ║              ║   Fail-fast behavior of an iterator cannot be guaranteed      ║
    ║   Fail-fast  ║ impossible to make any hard guarantees in the presence of     ║
    ║   behavior   ║           unsynchronized concurrent modification              ║
    ╠══════════════╬═════════════════════╦═══════════════════╦═════════════════════╣
    ║              ║                     ║                   ║                     ║
    ║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked    ║
    ║              ║                     ║                   ║       buckets       ║
    ╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣
    ║      Is      ║                                                               ║
    ║ synchronized ║              implementation is not synchronized               ║
    ╚══════════════╩═══════════════════════════════════════════════════════════════╝
    

提交回复
热议问题