Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap or HashMap faster [duplicate]

Tags:

I am writing an dictionary that make heavily use of String as key in Map<String, Index>. What I concern is which one of HashMap and TreeMap will result in better (faster) performance in searching a key in the map?

like image 655
Genzer Avatar asked Aug 14 '11 14:08

Genzer


People also ask

Is TreeMap or HashMap faster?

HashMap, being a hashtable-based implementation, internally uses an array-based data structure to organize its elements according to the hash function. HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains(). Therefore, it's significantly faster than a TreeMap.

Does TreeMap remove duplicates?

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

Will TreeMap allow duplicates?

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

Which is faster Map or HashMap?

HashMap does not maintain any insertion order of its elements hence it is quicker than Map. In contrast to Map, HashMap can hold duplicate values. It's possible to implement the Map interface by utilizing its implementing classes.


1 Answers

Given that there are not many collissions hashmaps will give you o(1) performance (with a lot of colissions this can degrade to potentially O(n) where N is the number of entries (colissions) in any single bucket). TreeMaps on the other hand are used if you want to have some sort of balanced tree structure which yields O(logN) retrieval. So it really depends on your particular use-case. But if you just want to access elements, irrespective of their order use HashMap

like image 121
LordDoskias Avatar answered Sep 22 '22 09:09

LordDoskias