Hey! Why does mutableMapOf return exactly LinkedHa...
# announcements
i
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?
6
w
I don’t really know. But a guess would be, if I’m not totally mistaken as well, that
LinkedHashMap
ensures the order which you insert elements, and
HashMap
not? So maybe because you are explicitly saying you have a
mutableMap
you will be adding/removing?! ¯\_(ツ)_/¯
t
Order is important. You can iterate over created map and order will be the same as in your code.
☝️ 1
r
https://discuss.kotlinlang.org/t/listof-arraylistof-setof-etc/1475/5
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.
w
Copy code
/**
 * Returns an empty new [MutableMap].
 *
 * The returned map preserves the entry iteration order.
 * @sample samples.collections.Maps.Instantiation.emptyMutableMap
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <K, V> mutableMapOf(): MutableMap<K, V> = LinkedHashMap()
It says in the comment that.
1
c
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