Arrays and Lists
The café menu has several drinks, and the till records many orders. Storing each in its own variable, drink1, drink2, drink3, falls apart the moment a new drink arrives. Kotlin offers arrays and lists to hold many values under one name.
The rule
Array: fixed slots. List: ordered items. Both count from zero.
Arrays have a size fixed at creation. You can change what is in a slot, but you cannot add or remove slots.
val menu = arrayOf("latte", "mocha", "chai")
menu[1] = "flat white" // change a slot: allowed
println(menu.size) // 3
val week = IntArray(7) // seven zeros, one per day
val doubles = Array(3) { it * 2 } // 0, 2, 4IntArray, DoubleArray and friends store plain numbers efficiently. Array(3) { it * 2 } fills each slot by running the braces with it as the index.
Lists are Kotlin's everyday choice. listOf makes a read-only list; mutableListOf makes one you can grow and shrink.
val drinks = listOf("latte", "mocha", "chai")
println(drinks[0]) // latte
println(drinks.first()) // latte
println(drinks.last()) // chai
println(drinks.indexOf("tea")) // -1: not found
println("chai" in drinks) // true
val orders = mutableListOf("latte")
orders.add("chai") // [latte, chai]
orders.removeAt(0) // [chai]Reading past the end, drinks[3], throws IndexOutOfBoundsException. drinks.getOrNull(3) returns null instead.
Two differences show up when printing and comparing. println(drinks) shows [latte, mocha, chai], but an array needs contentToString(). And == on two lists compares their items, while == on two arrays asks whether they are the same object; use contentEquals for arrays.
The shortcut
Ask "Will the number of items ever change?" Never, and you care about raw performance or a fixed shape → array. Otherwise → list. For indexes, remember the last index is size - 1.
Count from zero
In
listOf("latte", "mocha", "chai"), the indexes are 0, 1 and 2.
Drills
Answer fast — trust the rule.
val menu = arrayOf("latte", "mocha"). Which line does not compile?
What is listOf("a", "b", "c")[1]?
What does IntArray(3) contain?
listOf(1, 2) == listOf(1, 2) and arrayOf(1, 2) == arrayOf(1, 2). What are the results?
Remember
- Arrays have fixed slots; lists are the flexible everyday choice.
- Indexes run from 0 to
size - 1;getOrNullavoids crashes. - Print arrays with
contentToString()and compare them withcontentEquals.
