Skip to main content
Kotlin Basics
CHAPTER 10 Beginner

Arrays and Collections

Updated: May 18, 2026
5 min read

# CHAPTER 10

Arrays and Collections

1. Chapter Introduction

When building a shopping app, you don't create item1, item2, and item3 variables. You create a single list that holds *all* items. In this chapter, we will explore Collections. Kotlin provides several ways to group data: Arrays (fixed size), Lists (ordered items), Sets (unique items), and Maps (key-value pairs). Crucially, Kotlin enforces strict differences between *Mutable* (changeable) and *Immutable* (read-only) collections.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create and manipulate standard Arrays.
  • Understand the difference between Immutable and Mutable Collections.
  • Use listOf() and mutableListOf().
  • Use Sets (setOf) to ensure uniqueness.
  • Use Maps (mapOf) for Key-Value pairs.

3. Arrays (Fixed Size)

An Array is a container that holds a fixed number of values of a single type. Once an array is created, its size cannot grow or shrink.
kotlin
123456789101112131415
fun main() {
    // Creating an array using arrayOf()
    val numbers = arrayOf(10, 20, 30, 40)
    
    // Accessing elements via index (0-based)
    println("First element: ${numbers[0]}") // 10
    
    // Modifying an element
    numbers[1] = 99 
    
    // Iterating over an array
    for (num in numbers) {
        println(num)
    }
}

4. Collections: Immutable vs Mutable

In Java, standard Lists can always be modified (add/remove). This can lead to bugs if a list is passed to a function that secretly deletes items! Kotlin splits collections into two distinct interfaces:
  1. 1. Immutable (Read-Only): You can read items, but you cannot add, remove, or change them. (e.g., listOf()).
  1. 2. Mutable: You can add, remove, and change items. (e.g., mutableListOf()).

5. Lists (Ordered Collections)

Lists are the most common collection. They preserve the order of items and allow duplicates.

#### Read-Only List

kotlin
1234567
fun main() {
    // Immutable: Cannot add or remove items
    val colors = listOf("Red", "Green", "Blue")
    
    println(colors[0])
    // colors.add("Yellow") // ERROR! Unresolved reference: add
}

#### Mutable List

kotlin
123456789
fun main() {
    // Mutable: Can grow and shrink dynamically
    val shoppingList = mutableListOf("Apples", "Milk")
    
    shoppingList.add("Bread")       // Adds to the end
    shoppingList.remove("Apples")   // Removes the item
    
    println(shoppingList) // [Milk, Bread]
}

6. Sets (Unique Collections)

A Set is a collection that contains no duplicate elements. The order is generally not guaranteed.
kotlin
1234567
fun main() {
    val ids = mutableSetOf(101, 102, 103)
    
    ids.add(101) // We try to add a duplicate
    
    println(ids) // [101, 102, 103] - The duplicate was ignored!
}

7. Maps (Key-Value Pairs)

A Map (often called a Dictionary in other languages) stores data in pairs: a Key and a Value. Keys must be unique, but values can be duplicated.
kotlin
1234567891011
fun main() {
    // Creating a Mutable Map
    // "to" is a special Kotlin keyword to pair keys and values
    val userAges = mutableMapOf("Alice" to 28, "Bob" to 34)
    
    // Adding a new entry
    userAges["Charlie"] = 22
    
    // Reading a value
    println("Alice's age is ${userAges["Alice"]}")
}

8. Mini Project: Student Marks Manager

Let's build a program using a Map to store student grades.
kotlin
1234567891011121314151617
fun main() {
    val gradebook = mutableMapOf<String, Int>()
    
    // Adding students
    gradebook["Alice"] = 95
    gradebook["Bob"] = 82
    gradebook["Charlie"] = 88
    
    // Update Bob's grade
    gradebook["Bob"] = 85 
    
    println("--- CLASS GRADES ---")
    // Iterating through a Map
    for ((name, score) in gradebook) {
        println("Student: $name | Score: $score")
    }
}

9. Common Mistakes

  • Confusing val with Immutability: If you declare val list = mutableListOf("A"), the *variable reference* cannot change (you can't assign a whole new list to it), but you CAN still modify the contents (list.add("B")). val protects the reference; listOf() protects the contents!
  • IndexOutOfBounds: Trying to access numbers[5] in an array that only has 3 items will crash the program.

10. Best Practices

  • Default to Read-Only: Always use listOf() by default. Only upgrade to mutableListOf() if your specific business logic requires adding or removing items. Passing read-only lists between functions guarantees data integrity.

11. Exercises

  1. 1. Create a mutableListOf containing three names.
  1. 2. Add a fourth name to the list.
  1. 3. Remove the first name.
  1. 4. Use a for loop to print all remaining names.

12. MCQs with Answers

Question 1

What is the defining characteristic of an Array in Kotlin?

Question 2

What is the fundamental difference between listOf() and mutableListOf()?

Question 3

Which collection type strictly prohibits duplicate elements?

Question 4

What is the output of setOf(1, 1, 2, 3)?

Question 5

Which collection type stores data in Key-Value pairs?

Question 6

What keyword is used to link a Key to a Value when initializing a Map?

Q7. If you declare val list = mutableListOf(1, 2), can you do list.add(3)? a) Yes, because the list contents are mutable, even though the variable reference val is fixed b) No, val makes the contents immutable Answer: a) Yes.
Question 8

How do you access the value associated with the key "Bob" in a map?

Question 9

What happens if you try to call .add() on a collection created with listOf()?

Question 10

Why does Kotlin enforce a split between Mutable and Immutable collections?

13. Interview Questions

  • Q: Explain the difference between val myVar and listOf(). (Answer: val prevents the variable *reference* from being reassigned. listOf() prevents the *contents* of the collection from being altered).
  • Q: When would you use a Set instead of a List?

14. Summary

Collections are essential for handling dynamic data. Kotlin improves upon Java's collections by strictly separating read-only and mutable interfaces. By defaulting to immutable lists (listOf()), Kotlin developers write code that is inherently safer, preventing hidden bugs caused by functions unexpectedly modifying shared data structures.

15. Next Chapter Recommendation

Text manipulation is a massive part of programming. In Chapter 11: Strings in Kotlin, we will dive deep into Kotlin's powerful String functions, multi-line strings, and text processing capabilities.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·