简体   繁体   中英

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. 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. Additionally, the main operation for the scenario is search/contains which would take O(log n). Although there are faster search/contain operations eg HashMap, I need ordering. If I need to insert or delete an entry, I believe these operations are also O(log n).

To return a list of properties within a price range, I think I can use headSet() method?

However, I've read on some threads that I can store as a HashMap and create a TreeSet from the HashMap; 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. As for the range operations there is a method more suited for your needs - subMap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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