what difference of hashSetOf() and mutableSetOf() method in kotlin

115 Views Asked by At

when or where use hashSetOf() or mutableSetOf() method in kotlin or what difference of these? I know the hashSetOf() or mutableSetOf() are the mutable but in programming when or where we use them.

val number1 = mutableSetOf(1, 2, 7, 98, 45)
println(number1)

val number2 = hashSetOf(1, 2, 67, 90)
println(number2)
2

There are 2 best solutions below

0
Sajid On BEST ANSWER

Well, both are mainly used for creating sets. The main difference lies in the order of elements that you insert.

hashSetOf() has got no regard for the order of elements.

While mutableSetOf() keeps track of the specific order the elements are inserted.

Don't get confused by the keyword 'mutableSet' in the second one. Both of these are mutable.

So, this code:

val number1 = mutableSetOf(1, 2, 7, 98, 45)
println(number1) 

It will print all the elements in the order they were inserted i.e. 1, 2, 7, 98 and then 45.

While this code:

val number2 = hashSetOf(1, 2, 67, 90)
println(number2) 

It may print 1, 2, 67 and 90 in any random order.

Hope you got it!

0
Tenfour04 On

When you use mutableSetOf, you know that the Set will predictably return the elements in the same order they were added when you iterate it. This is because it is using a LinkedHashSet under the hood, although it is theoretically possible in the future this could be changed to a different class that implements MutableSet and iterates in a predictable order.

When you use hashSetOf, you are explicitly requesting a HashSet, not a LinkedHashSet, so the elements will not necessarily iterate in a predictable order. In the current implementation, they do not. However, HashSet generally performs better than LinkedHashSet since it doesn't need to track the insertion order.

HashSet implements the MutableSet interface, and LinkedHashSet is a subclass of HashSet. But mutableSetOf's return type is the less specific MutableSet type. The distinction could be relevant in situations where a function requests an argument of a HashSet specifically, although this situation should be extremely rare since it would be kind of a code smell.