MutableList
Creating a MutableList
mutableListOf(...) creates a list that supports adding, removing, and replacing elements after creation, unlike the read-only List from listOf().
Example: Creating a MutableList
fun main() {
val numbers = mutableListOf(1, 2, 3)
println(numbers)
}
Login to try C/C++/Java/PHP code in the editor
Adding Elements
.add(item) appends a new element to the end of the list, while .add(index, item) inserts it at a specific position, shifting later elements over.
Example: Adding Elements
fun main() {
val numbers = mutableListOf(1, 2, 3)
numbers.add(4)
numbers.add(0, 0)
println(numbers)
}
Login to try C/C++/Java/PHP code in the editor
Removing Elements
.remove(value) removes the first matching element by value, while .removeAt(index) removes the element at a specific position.
Example: Removing Elements
fun main() {
val numbers = mutableListOf(10, 20, 30, 40)
numbers.remove(20)
numbers.removeAt(0)
println(numbers)
}
Login to try C/C++/Java/PHP code in the editor
Updating Elements by Index
Assigning to list[index] = value replaces the element at that position directly, without needing to remove and re-add.
Note: Iterating with an index and modifying by index (not structurally) is safe; adding/removing while looping directly is not.
Example: Updating Elements by Index
fun main() {
val numbers = mutableListOf(1, 2, 3)
numbers[1] = 99
println(numbers)
}
Login to try C/C++/Java/PHP code in the editor
- Using
mutableListOf()when a plain read-onlylistOf()would be safer and clearer for data that never actually needs to change. - Modifying a
MutableListwhile iterating over it directly with aforloop, risking aConcurrentModificationException. - Forgetting
removeAt()takes an index whileremove()takes a value, and using the wrong one accidentally.
mutableListOf(...)creates aMutableList, supporting.add(),.remove(), and.removeAt()..add(item)appends an item to the end;.add(index, item)inserts at a specific position..remove(item)removes the first occurrence of a value;.removeAt(index)removes by position.- Modifying a mutable collection while directly iterating it with a
forloop can throw aConcurrentModificationException.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: