Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap or HashMap? [duplicate]

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?

like image 470
JeanK Avatar asked Mar 16 '11 17:03

JeanK


People also ask

Does TreeMap allow duplicate?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.

Does TreeMap remove duplicates?

TreeMap Features It allows only distinct keys. Duplicate keys are not possible.

When would a TreeMap be preferable to a HashMap?

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.

Why would anyone use TreeMap over HashMap?

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.


1 Answers

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.

like image 187
Jon Skeet Avatar answered Oct 06 '22 02:10

Jon Skeet