Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

MutableList vs ArrayList

MutableList is ArrayList in Kotlin currently.

Create an Empty MutableList

Below is the most idiomatical way to create an empty mutable list in Kotlin.

val mutableList = mutableListOf<Int>()
mutableList
[]

Another way to create an emtpy MutableList.

MutableList < Int > (0, {0})
[]

Create an MutableList with Initial Values

Create a MutableList containing 3 zeros.

val arrList = MutableList < Int > (3, {0})
arrList
[0, 0, 0]

Create a MutableList with initial values.

val mList = mutableListOf(1, 2, 3)
mList
[1, 2, 3]
listOf(0, 1, 2) + listOf(3, 4, 5)
[0, 1, 2, 3, 4, 5]
val list = listOf(0, 1, 2, 3, 4)
list
[0, 1, 2, 3, 4]
val arrList = mutableListOf(1, 2) + mutableListOf(3, 4)
arrList
[1, 2, 3, 4]
arrList.lastIndex
3
arrList.indices
0..3
arrList.add(1000)
Line_31.jupyter-kts (1:9 - 12) Unresolved reference: add
val mList1 = mutableListOf(1, 2, 3)
mList1
[1, 2, 3]
mList1.toCollection(mutableListOf())
[1, 2, 3]
val mList2 = mList1.toMutableList()
null

Verify that mList2 has the same elements as mList1.

mList2 == mList1
true

Verify that mList2 is a different object than mList1.

mList2 === mList1
false

Methods and Operators

addAll

val mList = mutableListOf(1, 2, 3)
mList
[1, 2, 3]
mList.addAll(listOf(4, 5, 6))
mList
[1, 2, 3, 4, 5, 6]
val mList1 = mList.subList(1, 3)
mList1
[2, 3]
mList1.add(100)
mList1
[2, 3, 100]
mList
[1, 2, 3, 100]
list.subList(1, 3)
[1, 2]
val mList2 = mList.slice(1 until 3)
mList2
[2, 3]
val mList3 = mList2 + mutableListOf(1000, 2000)
mList3
[2, 3, 1000, 2000]
list.take(3)
[0, 1, 2]
list.takeLast(2)
[3, 4]

data class is preferred over Tuple-like data.

ceil(2.3)
3.0