Table of contents
1.
Introduction
2.
Collection
3.
Array
4.
ArrayList
5.
List
6.
Mutable List
7.
Array List 
8.
FAQs
9.
Key Takeaways 
Last Updated: Mar 27, 2024

Kotlin Lists and Mutable Array

Author Pradeep Kumar
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss Collections in Kotlin. Collections are of two types: Mutable Collections and Immutable Collections. We will look into lists and see how you can declare a list and explore the various functionalities provided by a list.

We'll learn about arrays and how to declare and use them in a program and discuss the different kinds of functionalities supported by an Array. In the next section, we will study collections.

Collection

A collection contains several objects of the same data type. Objects in a collection are generally called elements or items. For example, all the people in a building form a collection.

In Kotlin, Collections are of two types, which are as follows:

  1. Immutable Collection: It only supports read-only functionality. Once initialized, you can not add or remove elements from an immutable collection.
  2. Mutable Collection: It supports both read and write functionality. A mutable collection allows you to add or remove elements. 

In the following sections, we will look at different types of arrays and lists in Kotlin. 

Array

The array is a collection of elements of similar data types such as Int, String, etc. Arrays in Kotlin are mutable and have a fixed size. As arrays are mutable in nature, we can perform both read and write operations on the array's elements.

In the example below, we will see different ways of initialising an array in kotlin:

// Different ways to initialise an array
fun main(){
    // Initialising an array having elements of different data types
    var arr1= arrayOf(1,2,3,4,"a","b")
    // Initialising an array having elements of integer data type
    var arr2= arrayOf<Int>(1,2,3,4)
    // Initialising an array having elements of string data type
    var arr3= arrayOf<String>("ab","bc","cd")

    // Traversing the arr1
    for(i in arr1){
        print("$i ");
    }
    println();
   
    for(i in arr2){
        print("$i ");
    }
    println();
   
    // Traversing the arr3
    for(i in arr3){
        print("$i ");
    }
}

Output:

1 2 3 4 a b
1 2 3 4
ab bc cd

In the example below, we will see how we can edit the elements of an array in Kotlin:

// In this function, we will see how we can change the value of an element in array
fun main(){
    var arr = arrayOf(1,2,3,4);
    arr[0]=10; // replacing element at 0th index with 10
    arr[1]=11; // replacing element at 1st index with 11
    for(element in arr){
        println(element)
    }
}

Output:

10
11
3
4

ArrayList

We use the ArrayList class to create a dynamic array. The size of an ArrayList can be decreased or increased, and it supports both read and write functionalities. 

In the example below, we will see how an arrayList is initialised in Kotlin:

// In this function, we will see how to initialise and add elements to an array list
fun main(){  
    val planets = ArrayList<String>()//Creating an empty arraylist  
    planets.add("Earth")//Adding object in arraylist  
    planets.add("Mars")  
    planets.add("Jupiter")  
    planets.add("Saturn")  
    // printing elements in the planets ArrayList
    for (planet in planets) {  
        println(planet)  
    }  
    // using the index function to print the index of mars
    println("Index of Mars is: " + planets.indexOf("Mars"))
    // Changing element at index 1
    planets.set(1,"Pluto")
    println("Element at index 1 is: " + planets[1])
}

Output:

Earth
Mars  
Jupiter
Saturn
Index of Mars is: 1
Element at index 1 is: Pluto

In this example, we will see how an element can be added to or removed from an arrayList

// In this function, we will see how we can remove an element from an arrayList
fun main(){  
    val squares = ArrayList<Int>()//Creating an empty arraylist  
    squares.add(1)//Adding object in arraylist  
    squares.add(4)  
    squares.add(9)  
    squares.add(16)  
    squares.add(25)
    print("Elements before deletion: ")  
    for (i in squares) {  
        print("$i ")  
    }  
    println()
    print("Elements after deletion: ")
    squares.remove(9)
    for (i in squares) {  
        print("$i ")  
    }  
}  

Output:

Elements before deletion: 1 4 9 16 25
Elements after deletion: 1 4 16 25

List

In Kotlin, a list is an ordered collection of elements. Immutable lists and mutable lists are the two types of lists in Kotlin. Immutable Lists can not be modified, but mutable lists are editable. Immutable Lists are read-only lists and are created with the listOf() method. Mutable Lists are editable and are created with the mutableListOf() method.

In this example, we will see the working of a list in Kotlin: 

// In this function, we will see the working of a list
fun main(){  
    // Initialising a list
    val cities = listOf("Delhi", "Mumbai", "Bangalore")
    // check if a element is part of the list or not
    println("Does the list contain Bangalore?: " + cities.contains("Bangalore"))
    // Calculating the size of list
    println("Size of cities list is: "+ cities.size)
    // Finding the index of a particular element
    println("Index of Delhi (in the list) is: "+ cities.indexOf("Delhi"))
    // Printing element at index 2
    println("Element at index 2 is: "+ cities[2])
}

Output:

Does the list contain Bangalore?: true
Size of cities list is: 3
Index of Delhi (in the list) is: 0
Element at index 2 is: Bangalore

Mutable List

It is mutable in nature. The methods of the MutableList supports both read and write functionalities. Once the elements in MutableList have been declared, more elements can be added to it or removed therefore it doesn't have a fixed size.

In the example below, we will see different ways of initialising a mutable List in Kotlin:

// In this function, we will see different ways of initialising a mutable List
fun main(){  
    //Initialising a mutable list 
    var mutableArr1 = mutableListOf(1,2,3,4,"a","b")
    //Initialising a mutable list having elements of integer data type
    var mutableArr2= mutableListOf<Int>(1,2,3,4)
    //Initialising a mutable list having elements of string data type
    var mutableArr3=mutableListOf<String>("ab","bc","cd")

    // Traversing the mutableArr1
    for(i in mutableArr1){
        print("$i ");
    }
    println();
   
    // Traversing the mutableArr2
    for(i in mutableArr2){
        print("$i ");
    }
    println();
   
    // Traversing the mutableArr3
    for(i in mutableArr3){
        print("$i ");
    }
}

Output:

1 2 3 4 a b
1 2 3 4
ab bc cd

In this example, we will see some basic functionality supported by a mutable List:

// In this function, we will see how we can check if a mutableList contains a particular element or not
fun main(){  
    // Initialising a mutable list
    var mutableArr1 = mutableListOf(1,2,3,4,"a","b")
    var key=4
    println("Does the list contain $key?: " + mutableArr1.contains(key))
}

Output:

Does the list contain 4?: true

Array List 

ArrayList is mutable in nature and provides both read and write functionalities. We use the arrayListOf() method to create an arrayList in Kotlin. For example, 

// In this function, we will see how we can create and iterate an arrayList
fun main(){  
    val squares: ArrayList<Int> = arrayListOf<Int>()  
   
    // adding elements to the arrayList
    squares.add(1)  
    squares.add(4)  
    squares.add(9)  
 
    println(".......printing ArrayList.......")
    // Iterating over the array  
    val itr = squares.iterator()  
    // check if there is a next element
    while(itr.hasNext()) {
        println(itr.next())  
    }  
}

Output:

.......printing ArrayList.......
1
4
9

Must Read Elvis Operator Kotlin

Must Read Difference between ArrayList and LinkedList


FAQs

  1. What is the difference between lists obtained using listOf() and mutableList() methods?
    The list obtained by using the listOf() method is immutable, while the list returned by the mutableList() method is mutable.
     
  2. What is the fundamental difference between an array and a Mutable List in Kotlin?
    Array is fixed size, while the size of a Mutable List can be changed according to requirements.
     
  3. Is the array mutable or immutable in Kotlin?
    Arrays in Kotlin are mutable.

Key Takeaways 

Cheers if you reached here!!!

In this blog, we discussed collections and their types: Mutable Collections and Immutable Collections. We also looked at different kinds of arrays and lists. We saw how they can be declared and how we can add or remove elements from them. 

Recommended Reading:

Difference Between List and Set

After reading this blog, I believe you will work with Lists and Arrays smoothly. If you wish to learn collections in detail, then you can check out our other blog on Kotlin Collections. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website.

Live masterclass