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.
I need a data structure to store users which should be retrieved by id.
Share
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.
HashMapuses hash codes to store things so you have constant time forputandgetoperations but items are always unordered.TreeMapinstead uses a binary tree so you have log(n) time for basic operations but items are kept ordered in the tree.I would use
HashMapbecause 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 usingConcurrentHashMap.A middle approach is the
LinkedHashMapthat uses same structure asHashMap(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 ofTreeMap.