在Java中,哪种是字典数据结构中最推荐的类? [英] In Java, which is the most recommended class for a dictionary data structure?
问题描述
我需要一个数据结构来存储应该通过id检索的用户。
我注意到有几个实现Map界面的类。哪一个应该是我的默认选择?他们似乎都相当于我。
可能取决于您计划拥有的用户数量,如果您需要订购或只需通过id获取单个项目
HashMap
使用哈希码存储东西,所以你有不断的时间为 put
和获取
操作,但项目始终是无序的。
TreeMap
代替使用二进制树,因此您可以在基本操作中使用日志(n),但项目将保存在树中。
我将使用 HashMap
,因为它更简单(请记住给它一个合适的初始容量)。请记住,这些数据结构在默认情况下不会同步,如果您打算从多个线程中使用它们,请使用 ConcurrentHashMap
。
中间方法是使用与 HashMap
(hashcode和equals方法)相同的结构的 LinkedHashMap
它还保留了在图中插入的元素的双向链接列表(插入的顺序)。这个混合物已经订购了项目(按照注释意义排序,按照意见建议),但是我已经指定了),而没有性能损失 TreeMap
。 / p>
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.
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
.
这篇关于在Java中,哪种是字典数据结构中最推荐的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!