简体   繁体   English

哈希图,哈希集,树图,树集-选择

[英]hash map, hash set, tree map, tree set - which to choose

I am trying to justify whether I'm using the most appropriate Data Structure for a set of scenarios. 我试图证明我是否针对一组场景使用了最合适的数据结构。

The first scenario is an estate agent selling properties at different prices where no price is duplicated. 第一种情况是房地产经纪人以不同的价格出售物业,没有重复的价格。 Customers choose a range of prices & obtain a list of properties in that range. 客户选择价格范围并获取该范围内的物业清单。

To store the collection of property data I would choose TreeSet. 为了存储属性数据的集合,我将选择TreeSet。 As no property will have the same price, I could have pairs of: price (key) and value (property details). 由于没有财产具有相同的价格,因此我可以使用以下对:价格(关键)和价值(属性详细信息)。 This would work with a TreeSet because there are no duplicate entries and the TreeSet could sort price in natural order. 这将适用于TreeSet,因为没有重复的条目,并且TreeSet可以按自然顺序对价格进行排序。 Additionally, the main operation for the scenario is search/contains which would take O(log n). 此外,该场景的主要操作是搜索/包含O(log n)。 Although there are faster search/contain operations eg HashMap, I need ordering. 尽管有更快的搜索/包含操作,例如HashMap,但我需要排序。 If I need to insert or delete an entry, I believe these operations are also O(log n). 如果我需要插入或删除条目,我相信这些操作也是O(log n)。

To return a list of properties within a price range, I think I can use headSet() method? 要返回价格范围内的属性列表,我想可以使用headSet()方法吗?

However, I've read on some threads that I can store as a HashMap and create a TreeSet from the HashMap; 但是,我已经阅读了一些可以存储为HashMap并可以从HashMap创建TreeSet的线程。 would it be worth doing this? 这样做值得吗?

You need an ordered set to be able to serve this type of queries. 您需要一个有序集合才能服务于此类查询。 Therefor a tree structure is better suited for your needs than a hash map. 因此,树形结构比哈希图更适合您的需求。 However the equivalent to a HashMap is TreeMap, not a TreeSet - you need a mapping between key and value. 但是,等效于HashMap的是TreeMap,而不是TreeSet-您需要键和值之间的映射。 As for the range operations there is a method more suited for your needs - subMap . 至于范围操作,有一种更适合您需求的方法-subMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM