Google News
logo
Kotlin - Interview Questions
What is the difference between 'listOf', 'mutableListOf', and 'arrayListOf' in Kotlin?
In Kotlin, `listOf`, `mutableListOf`, and `arrayListOf` are functions used to create different types of lists.

Here's the difference between them :

1. `listOf` :
   * The `listOf` function creates an immutable list (read-only) in Kotlin.
   * The elements of the list cannot be modified once the list is created.
   * It returns an instance of `List<T>`, where `T` is the type of the elements in the list.
   Example:
     val immutableList = listOf("apple", "banana", "orange")​

2. `mutableListOf` :
   * The `mutableListOf` function creates a mutable list in Kotlin.
   * The elements of the list can be modified (added, removed, or modified) after the list is created.
   * It returns an instance of `MutableList<T>`, where `T` is the type of the elements in the list.
   Example :
     val mutableList = mutableListOf("apple", "banana", "orange")
     mutableList.add("grape")
     mutableList.removeAt(0)​

3. `arrayListOf` :
   * The `arrayListOf` function is similar to `mutableListOf` and creates a mutable list in Kotlin.
   * It returns an instance of `ArrayList<T>`, which is a specific implementation of `MutableList<T>`.
   * The elements of the list can be modified, and `ArrayList` provides additional functionality and performance optimizations compared to a regular mutable list.
   Example :
     val arrayList = arrayListOf("apple", "banana", "orange")
     arrayList.add("grape")
     arrayList.removeAt(0)​
Advertisement