Hey! Why does mutableMapOf return exactly LinkedHa...
# announcements
Hey! Why does mutableMapOf return exactly LinkedHashMap, not a simple HashMap? upd.: I understand why mutableListOf returns ArrayList - it is the most frequently used implementation of MutableList... But why do we need LinkedHashMap? By what criterion is it better than plain HashMap?
I don’t really know. But a guess would be, if I’m not totally mistaken as well, that
ensures the order which you insert elements, and
not? So maybe because you are explicitly saying you have a
you will be adding/removing?! ¯\_(ツ)_/¯
Order is important. You can iterate over created map and order will be the same as in your code.
☝️ 1
Long time ago we defaulted all maps and sets to be linked because it was really confusing to loose order in many practical applications.
If you want a hashset for performance/memory reasons you can obtain it with hashSetOf() or toHashSet() functions.
You cannot change the default behavior of setOf in the standard library, but if you really want, you can hide it with your own explicitly imported setOf function (import my.utils.setOf), though I wouldn’t recommend it as a long term solution.
Copy code
 * Returns an empty new [MutableMap].
 * The returned map preserves the entry iteration order.
 * @sample samples.collections.Maps.Instantiation.emptyMutableMap
public inline fun <K, V> mutableMapOf(): MutableMap<K, V> = LinkedHashMap()
It says in the comment that.
If you have iteration order maintained but don’t actually need it, then it’s not much of a loss. But if iteration order is not maintained and you do need it, it is a much bigger problem, and harder to correct for later. Performance isn’t impacted significantly between the two, so it makes more sense to just go with the conservative choice and use the LinkedHashMap