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]:
Create a MutableList with initial values.
In [1]:
val mList = mutableListOf(1, 2, 3)
mList
Out[1]:
In [2]:
listOf(0, 1, 2) + listOf(3, 4, 5)
Out[2]:
In [9]:
val list = listOf(0, 1, 2, 3, 4)
list
Out[9]:
In [33]:
val arrList = mutableListOf(1, 2) + mutableListOf(3, 4)
arrList
Out[33]:
In [34]:
arrList.lastIndex
Out[34]:
In [36]:
arrList.indices
Out[36]:
In [32]:
arrList.add(1000)
In [10]:
val mList1 = mutableListOf(1, 2, 3)
mList1
Out[10]:
In [12]:
mList1.toCollection(mutableListOf())
Out[12]:
In [11]:
val mList2 = mList1.toMutableList()
Out[11]:
Verify that mList2 has the same elements as mList1.
In [12]:
mList2 == mList1
Out[12]:
Verify that mList2 is a different object than mList1.
In [13]:
mList2 === mList1
Out[13]:
Methods and Operators¶
addAll¶
In [17]:
val mList = mutableListOf(1, 2, 3)
mList
Out[17]:
In [14]:
mList.addAll(listOf(4, 5, 6))
mList
Out[14]:
In [19]:
val mList1 = mList.subList(1, 3)
mList1
Out[19]:
In [20]:
mList1.add(100)
mList1
Out[20]:
In [21]:
mList
Out[21]:
In [12]:
list.subList(1, 3)
Out[12]:
In [24]:
val mList2 = mList.slice(1 until 3)
mList2
Out[24]:
In [27]:
val mList3 = mList2 + mutableListOf(1000, 2000)
mList3
Out[27]:
In [10]:
list.take(3)
Out[10]:
In [11]:
list.takeLast(2)
Out[11]:
data class is preferred over Tuple-like data.
In [3]:
ceil(2.3)
Out[3]:
In [ ]:
References¶
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-list-of.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html
https://stackoverflow.com/questions/46846025/how-to-clone-or-copy-a-list-in-kotlin/52907983