In the Kotlin collection functions, we have
setOf
, mutableSetOf
, sortedSetOf
, linkedSetOf
and hashSetOf
.
The first 3 is understood their differences. But what's the last two? How are they different from others and from themselves?
You know that linkedSetOf
returns a LinkedHashSet
whereas hashSetOf
returns a HashSet
. The difference between LinkedHashSet
and HashSet
is that LinkedHashSet
maintains the order of elements with which they were either inserted into or removed from the set whereas HashSet
doesn't maintain the order.
Observe the example below (Kotlin playground, if you want to see it in action)
val set: LinkedHashSet<Int> = linkedSetOf(1, 3, 2)
println(set) // [1, 3, 2]
set.remove(3)
set += listOf(5, 4)
println(set) // [1, 2, 5, 4]
val hashSet: HashSet<Int> = hashSetOf(1, 3, 2)
println(hashSet) // [1, 2, 3]
hashSet.remove(3)
hashSet += listOf(5, 4)
println(hashSet) // [1, 2, 4, 5]
If you look at how the set is printed in different instances of addition and removal of elements, you would see that in the case of LinkedHashSet
, the order in which the elements were added or removed is maintained and printed in the same order when iterated over.
Note: Just to show that HashSet
doesn't sort the elements, below is an example (Kotlin playground)
val linkedHashSet = linkedSetOf("aaa","bbb","ccc")
println(linkedHashSet) // [aaa, bbb, ccc]
linkedHashSet.remove("ccc")
linkedHashSet += listOf("ddd","zzz")
println(linkedHashSet) // [aaa, bbb, ddd, zzz]
val hashSet = hashSetOf("aaa","bbb","ccc")
println(hashSet) // [aaa, ccc, bbb]
hashSet.remove("ccc")
hashSet += listOf("ddd","zzz")
println(hashSet) // [aaa, bbb, zzz, ddd]