When to use hashmaps or treemaps?
I know that I can use TreeMap to iterate over the elements when I need them to be sorted. But is just that? There is no optimization when I just want to consult the maps, or some optimal specific uses?
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
TreeMap Features It allows only distinct keys. Duplicate keys are not possible.
It provides a performance of O(1) , while TreeMap provides a performance of O(log(n)) to add, search, and remove items. Hence, HashMap is usually faster. A TreeMap uses memory way more effective so it is a good Map implementation for you if you are not sure of elements quantity that have to be stored in memory.
TreeMap provides a performance of O(log(n)) for most operations like add(), remove() and contains() A Treemap can save memory (in comparison to HashMap) because it only uses the amount of memory needed to hold its items, unlike a HashMap which uses contiguous region of memory.
TreeMap
provides guaranteed O(log n) lookup time (and insertion etc), whereas HashMap
provides O(1) lookup time if the hash code disperses keys appropriately.
Unless you need the entries to be sorted, I'd stick with HashMap
. Or there's ConcurrentHashMap
of course. I can't remember the details of the differences between all of them, but HashMap
is a perfectly reasonable "default" option :)
For completeness, I should point out that there was a discussion on Stack Overflow a month or so ago about the internals of various maps. See the comments in this question, which I will copy into this answer if bestsss is happy for me to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With