Difference between HashMap, LinkedHashMap and TreeMap

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

    All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes are the time guarantees and the ordering of the keys.

    1. HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists.
    2. TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface.TreeMap is implemented by a Red-Black Tree.
    3. LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.

    Imagine you passed an empty TreeMap, HashMap, and LinkedHashMap into the following function:

    void insertAndPrint(AbstractMap map) {
      int[] array= {1, -1, 0};
      for (int x : array) {
        map.put(x, Integer.toString(x));
      }
      for (int k: map.keySet()) {
       System.out.print(k + ", ");
      }
    }
    

    The output for each will look like the results below.

    For HashMap, the output was, in my own tests, { 0, 1, -1}, but it could be any ordering. There is no guarantee on the ordering.
    Treemap,the output was,{ -1, 0, 1}
    LinkedList,the output was,{ 1, -1, 0}

提交回复
热议问题