I need a data structure to store users which should be retrieved by id. I noticed there are several classes that implement the Map interface. Which one should be my default choice? They all seem quite equivalent to me.
If we want both operations, look up and prefix search, Trie is suited. With Trie, we can support all operations like insert, search, delete in O(n) time where n is length of the word to be processed. Another advantage of Trie is, we can print all words in alphabetical order which is not possible with hashing.
The Dictionary class is the abstract parent of any class, such as Hashtable , which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up.
A Java dictionary is an abstract class that stores key-value pairs. Given a key, its corresponding value can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. The Dictionary object classes are implemented in java. util .
Different languages enforce different type restrictions on keys and values in a dictionary. Dictionaries are often implemented as hash tables.
Probably it depends on how many users you plan to have and if you will need them ordered or just getting single items by id.
HashMap
uses hash codes to store things so you have constant time for put
and get
operations but items are always unordered.
TreeMap
instead uses a binary tree so you have log(n) time for basic operations but items are kept ordered in the tree.
I would use HashMap
because it's the simpler one (remember to give it a suitable initial capacity). Remember that these datastructures are not synchronized by default, if you plan to use it from more than one thread take care of using ConcurrentHashMap
.
A middle approach is the LinkedHashMap
that uses same structure as HashMap
(hashcode and equals method) but it also keeps a doubly linked list of element inserted in the map (mantaining the order of insertion). This hybrid has ordered items (ordered in sense of insertion order, as suggested by comments.. just to be precise but I had already specified that) without performance losses of TreeMap
.
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