I would like to append an element to an IntArray, ...
# getting-started
o
I would like to append an element to an IntArray, how would I do it in something simpler than this?
Copy code
var result = intArrayOf(1, 2, 3, 4)

val list = result.toMutableList()
list.add(5)

result = list.toIntArray
a
intArrayOf(1, 2, 3, 4) + 5
😮 4
👍🏻 1
o
wat
i really didnt know you could do that
e
also
intArrayOf(1, 2, 3, 4) + intArrayOf(5)
it's all just wrapping the creating of a new array and copying, no magic involved…
t
so in your case it could also be
result += 5
c
Do note that these solutions will copy the array. If you want to append an element often with good performance, use ArrayList (which will essentially do the same thing but is more clever about what and when to copy, so it's much much faster)
👍 1
e
agreed. mutableListOf()/.toMutableList()/etc. are implemented by ArrayList so you are safe to just use those as normal
but there is no unboxed list built into Kotlin, so there may be some cases where primitive arrays are useful
c
Primitive arrays are a very slight bit faster, but if you need to append elements they are slower. In practice the difference in performance is so small between ArrayList and Array that in 99% of cases it's not worth using primitive arrays.
e
trove4j does have primitive (unboxed) lists that have amortized growth just like ArrayList (and of course you could build your own). there are cases in which that is actually worth it over the boxing of ArrayList. but yeah, most of the time MutableList<Int> is fine
c
Ah, I didn't get that you mentioned boxing as in Ints being boxed, I thought you meant the whole array being boxed (in the ArrayList instance), which is really damn cheap. If you have a really big array of primitives, the memory difference can be important, yeah. Hopefully Valhalla will solve all of this though.
124 Views