androidkotlinhashsetdifference

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


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)

Solution

  • 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!