0
0
Kotlinprogramming~5 mins

List creation (listOf, mutableListOf) in Kotlin

Choose your learning style9 modes available
Introduction

Lists help you keep many items together in order. You use listOf to make a list you cannot change, and mutableListOf to make a list you can change later.

When you want to store a fixed set of names that won't change.
When you need a list of numbers that you will add or remove items from.
When you want to keep a shopping list that you can update.
When you want to group related data like colors or days of the week.
When you want to pass a list of items to a function without changing it.
Syntax
Kotlin
fun main() {
    val fixedList = listOf<Type>(item1, item2, item3)
    val changeableList = mutableListOf<Type>(item1, item2, item3)
}

listOf creates a list that cannot be changed (read-only).

mutableListOf creates a list that you can add, remove, or change items in.

Examples
This creates an empty list of strings that cannot be changed.
Kotlin
val emptyList = listOf<String>()
A list with one number, fixed and unchangeable.
Kotlin
val singleItemList = listOf(42)
A list you can add items to after creating it.
Kotlin
val mutableList = mutableListOf("apple", "banana")
mutableList.add("cherry")
Start with an empty mutable list and add an item later.
Kotlin
val mutableEmptyList = mutableListOf<Int>()
mutableEmptyList.add(10)
Sample Program

This program shows how to create a fixed list and a mutable list. It prints the fixed list, then adds and removes items from the mutable list, printing the list each time.

Kotlin
fun main() {
    // Create a fixed list of fruits
    val fruits = listOf("apple", "banana", "cherry")
    println("Fixed list of fruits: $fruits")

    // Create a mutable list of numbers
    val numbers = mutableListOf(1, 2, 3)
    println("Mutable list before adding: $numbers")

    // Add a number to the mutable list
    numbers.add(4)
    println("Mutable list after adding: $numbers")

    // Remove a number from the mutable list
    numbers.remove(2)
    println("Mutable list after removing: $numbers")
}
OutputSuccess
Important Notes

Time complexity: Accessing items by index is fast (O(1)). Adding or removing items in mutableListOf is usually fast but can be slower if the list needs to resize.

Space complexity: Lists use space proportional to the number of items they hold.

A common mistake is trying to add or remove items from a list created with listOf, which is not allowed.

Use listOf when you want a list that should not change, and mutableListOf when you need to change the list after creating it.

Summary

listOf creates a fixed, read-only list.

mutableListOf creates a list you can change by adding or removing items.

Choose the right list type based on whether you need to change the list later.