Difference between HashMap, LinkedHashMap and TreeMap

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

    @Amit: SortedMap is an interface whereas TreeMap is a class which implements the SortedMap interface. That means if follows the protocol which SortedMap asks its implementers to do. A tree unless implemented as search tree, can't give you ordered data because tree can be any kind of tree. So to make TreeMap work like Sorted order, it implements SortedMap ( e.g, Binary Search Tree - BST, balanced BST like AVL and R-B Tree , even Ternary Search Tree - mostly used for iterative searches in ordered way ).

    public class TreeMap
    extends AbstractMap
    implements SortedMap, Cloneable, Serializable
    

    In NUT-SHELL HashMap : gives data in O(1) , no ordering

    TreeMap : gives data in O(log N), base 2. with ordered keys

    LinkedHashMap : is Hash table with linked list (think of indexed-SkipList) capability to store data in the way it gets inserted in the tree. Best suited to implement LRU ( least recently used ).

提交回复
热议问题