What is the difference between a HashMap and a TreeMap?

This question already has an answer here:

  • Difference between HashMap, LinkedHashMap and TreeMap 16 answers

  • TreeMap is an example of a SortedMap , which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.

    HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap , you can't be sure what order they will be in.

    HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.


    HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree . The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.

    Take a look at following diagram.

    在这里输入图像描述


    To sum up:

  • HashMap: Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted
  • TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted
  • Taken from: HashMap vs. TreeMap

    链接地址: http://www.djcxy.com/p/92168.html

    上一篇: TreeMap或HashMap?

    下一篇: HashMap和TreeMap有什么区别?