Maybe a dumb question, but is there such a thing as a Map in Kotlin where you only need to specify t...
c
Maybe a dumb question, but is there such a thing as a Map in Kotlin where you only need to specify the type of Key because you never actually plan on using the value? Or is there a different data structure that allows you to have constant time inserts and lookups? Example: I just want to know if I already "saw" a number in a list that I'm traversing, so I'm currently saving the fact that I saw it as a mapOf<Int, Boolean>, but the very existence of the Int would suffice and so the boolean seems redundant
OoooH. looks like hashSet is what I want. A bit confusing that mutableHashSet doesn't exist, while hashSet does?
j
well
hashSetOf
is the mutable version so there wouldn't exist a
mutableHashSet
, if you wanted an "immutable" set you'd call
setOf
which is just a
LinkedHashSet
cast to an immutable type
It is interesting there is an immutable version for the ordered set but no immutable version for an unordered
(and by immutable, it's really just read-only)
r
mutableSetOf
would do wouldn’t it? You don’t care about the implementation.
1
j
Yeah a
Set
(or
MutableSet
) is what you want. As for the factory function, just like for lists and maps, use
setOf
for a read-only structure,
mutableSetOf
for a mutable structure.
hashSetOf
,
arrayListOf
and the likes are really for cases when the exact implemation matters, which is almost never the case
c
Interesting. Well if I wanted constant time lookups and inserts, wouldn't I want to specify a hashSet then?
r
On the JVM,
setOf
and
mutableSetOf
both return a
LinkedHashMap
LinkedHashSet
under the hood, so they are constant time for
contains
(and for
add
and
remove
in the mutable case). They would never switch it to an implementation that performs worse in the general case. Specifying collection implementations is almost certainly premature optimisation based on insufficient information. Use the defaults until you have a proof that you need something else.
👍🏻 1
👍 1
c
Interesting. I didn't know that a set was implemented with a hash map. I thought a set was pretty much a list that prevented duplicates.
r
Ugh, I mistyped...
setOf
and
mutableSetOf
are backed by
LinkedHashSet
, not
LinkedHashMap
. Sorry. (Though it could be; implementing
Set
using a
Map
as you did is supported directly on the JVM - see
java.util.Collections.newSetFromMap
. I use that passing it a
ConcurrentHashMap
when I want a concurrent mutable set as so:
val concurrentSet: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
)