'What is the difference between the hash-map and array-map in clojure?
Clojure has an array-map and hash-map, I couldn't figure out the difference between the two. Could anyone explain if possible with an example as to when either of them would be used?
Solution 1:[1]
Array maps and hash maps have the same interface, but array maps have O(N) lookup complexity (i.e. it is implemented as an simple array of entries), while hash maps have O(1) lookup complexity.
Array maps have the advantage (which you don't need most of the time) that they maintain insertion order, so when you perform any operation that iterates over the map (say, map or reduce), you can process the entries in the same order as when you inserted them.
Note that if you "modify" (in the persistent-collection sense) an array map repeatedly, at some point it will become a hash map. e.g.
user=> (type (apply assoc (array-map) (zipmap (range 10) (range 10))))
clojure.lang.PersistentArrayMap
user=> (type (apply assoc (array-map) (zipmap (range 100) (range 100))))
clojure.lang.PersistentHashMap
Basically, always prefer hash maps if you don't care about key order. Also, if you do use array maps, keep in mind the lookup performance tradeoff.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
