Ben Chuanlong Du's Blog

It is never too late to learn.

MutableList in Kotlin

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.

In [2]:
val mutableList = mutableListOf<Int>()
mutableList
Out[2]:
[]

Another way to create an emtpy MutableList.

In [13]:
MutableList < Int > (0, {0})
Out[13]:
[]

Create an MutableList with Initial Values

Create a MutableList containing 3 zeros.

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

Create a MutableList with initial values.

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

Verify that mList2 has the same elements as mList1.

In [12]:
mList2 == mList1
Out[12]:
true

Verify that mList2 is a different object than mList1.

In [13]:
mList2 === mList1
Out[13]:
false

Methods and Operators

addAll

In [17]:
val mList = mutableListOf(1, 2, 3)
mList
Out[17]:
[1, 2, 3]
In [14]:
mList.addAll(listOf(4, 5, 6))
mList
Out[14]:
[1, 2, 3, 4, 5, 6]
In [19]:
val mList1 = mList.subList(1, 3)
mList1
Out[19]:
[2, 3]
In [20]:
mList1.add(100)
mList1
Out[20]:
[2, 3, 100]
In [21]:
mList
Out[21]:
[1, 2, 3, 100]
In [12]:
list.subList(1, 3)
Out[12]:
[1, 2]
In [24]:
val mList2 = mList.slice(1 until 3)
mList2
Out[24]:
[2, 3]
In [27]:
val mList3 = mList2 + mutableListOf(1000, 2000)
mList3
Out[27]:
[2, 3, 1000, 2000]
In [10]:
list.take(3)
Out[10]:
[0, 1, 2]
In [11]:
list.takeLast(2)
Out[11]:
[3, 4]

data class is preferred over Tuple-like data.

In [3]:
ceil(2.3)
Out[3]:
3.0
In [ ]:

Comments