Hi all. How can I create a List with initial capac...
# getting-started
d
Hi all. How can I create a List with initial capacity in Kotlin similar to Java? It seems the mutableListOf method only has elements parameter.
v
dineshbob:
MutableList<String>(n, {""})
d
Thanks Daniil. And it looks like the list has to be initialized inside the lamda itself, right?
v
Not sure what you meant by initializing, here are the docs: http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list.html
j
You would have to use the ArrayList constructor:
val list = ArrayList(size)
I think the reason is because you can't make an assumption about what implementation mutableListOf gives you
E.g if it gives you a linked list which doesn't have a size initialiser
v
@jk `MutableList`function was added in 1.1 and works the same as
ArrayList
j
My point is that the name MutableList just indicates "a list, that is mutable". If they wanted to change the underlying implementation in the future they could do
Although
MutableList<String>(n, {""})
will work fine - @dineshbob it's just initialising the first n as "", you can still mutate it after initialisation
d
Thanks @jk @voddan . If the ArrayList is created with an initial size, we can just call add() to add the elements. But if we create
MutableList<String>(n, {""}
then the List is initialized with empty strings. If we call add() to add the elements now, they are added after the empty strings. I see that's one big difference.
So is it ok to use the Java's
ArrayList(size)
directly in the Kotlin world? I thought that's not advised in Kotlin.
m
@dineshbob i don't think it is a bad practice. You could instantiate an ArrayList without any issue 😉
j
Kotlin has it's own ArrayList that implements MutableList: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html
d
whoa. looks like there are two ArrayList. One for JVM which is type alias to Java's ArrayList, and another one for JS which implements MutableList
j
Oh I didn't notice that! So on JVM it doesn't implement MutableList?
d
In this document they say to use the methods such as mutableListOf to create the Lists: https://kotlinlang.org/docs/reference/collections.html @muhil
j
Yes, using MutableList should be the default when you need a mutable list
But since you seem to specifically want to use an ArrayList type structure where you specify an initial capacity of the underlying array, using the a specific ArrayList is fine
👍 1
d
Okay. that makes sense. Thanks 🙂
👍 1
v
on JVM it doesn't implement MutableList?
It does. The type hierarchy does not depend on the target platform. The types are mapped. Details: http://kotlinlang.org/docs/reference/java-interop.html#mapped-types
👍 1
428 Views