What is the difference between a HashMap and a TreeMap?
This question already has an answer here:
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:
Taken from: HashMap vs. TreeMap
链接地址: http://www.djcxy.com/p/92168.html上一篇: TreeMap或HashMap?