Getting the size of a list
A Kotlin list reports how many elements it holds through its size property. It is a property, so it is written without parentheses: list.size, never list.size().
Unlike an array, a mutable list can change size, and size always reflects the current count:
val ourArray = mutableListOf(50, 40, 30)
println(ourArray.size)
ourArray.removeAt(2)
println(ourArray.size)
3
2
Removing the element at index 2 leaves two elements, so the second println prints 2.
Using the size to reach the end
Indices start at 0, so the last valid index is size - 1. Computing it from size keeps the code correct when the list grows or shrinks:
val ourArray = mutableListOf(50, 40, 30)
val size = ourArray.size
println(ourArray[size - 1])
println(ourArray[size - 2])
30
40
Kotlin lists also have last() and lastIndex as shortcuts. This lesson uses size to make the arithmetic visible.
Size versus last index
The size counts elements, and the last index is one less. A list of 4 ages has size 4 and valid indices 0 to 3. Because the first index is 0, a list of size n has exactly n valid indices, ending at n - 1.
The size is also the number of times a loop over the whole list runs. Remembering that keeps "size" and "last index" apart.
The exercise
The starter code:
val fruits = mutableListOf("mango", "kiwi", "grapefruit")
val ages = mutableListOf(14, 32, 50, 21)
- Print the size of
fruits. The list holds three items, so this prints3. - Print the last age. Index the list with
ages.size - 1, which is 3 for four items. It prints21. - Print the second to last age. Use
ages.size - 2, which is index 2. It prints50.
val fruits = mutableListOf("mango", "kiwi", "grapefruit")
val ages = mutableListOf(14, 32, 50, 21)
println(fruits.size)
println(ages[ages.size - 1])
println(ages[ages.size - 2])
3
21
50
Why use the size instead of a number
If the list gains a fifth element when you edit the program, ages[ages.size - 1] still reads the last one, while ages[3] silently reads the fourth. Code that asks the list for its size has one fewer place to update when the data changes.
Size, capacity and count
An ArrayList may keep spare room inside so that adding items is fast, but that spare room is not part of the list. The size property counts only the elements you added and not yet removed, which is the number that matters for indexing.
Size after adding and removing
Each add raises the size by one, and each removeAt or successful remove lowers it by one. Starting from an empty list, three calls to add followed by one removeAt(0) leave a size of 2. Replacing an element by index, as in ages[0] = 9, doesn't change the size, because no element was added or removed.
Since the size moves with the list, an index computed from it stays correct after the list changes, as long as you compute it again after the change.
Common mistakes
- Adding parentheses.
fruits.size()doesn't compile in Kotlin, becausesizeis a property rather than a method. - Reading at
size.ages[ages.size]is one past the end and throwsIndexOutOfBoundsException. - Using a stale size. A value saved in
val size = ages.sizedoesn't update when the list changes. Read the property again after adding or removing items. - Empty lists. With no elements,
size - 1is -1, andages[-1]throws. Check that the list is not empty first.
Checking for an empty list
A size of 0 means the list is empty. You can compare size to 0, but Kotlin has clearer functions: isEmpty() and isNotEmpty(). They are worth using before reading from the end of a list, since an empty list has no last element.
val items = mutableListOf<Int>()
println(items.isEmpty())
items.add(1)
println(items.size)
println(items.isEmpty())
true
1
false
Looping with the size
A loop over the positions of a list runs from 0 until size. The size is read again whenever the range is created, so the loop matches the list as it is at that moment:
val ages = mutableListOf(14, 32, 50, 21)
for (i in 0 until ages.size) {
println(ages[i])
}
14
32
50
21
Writing ages.indices gives the same range with less to type.
Key takeaways
list.sizeis the current number of elements.- The last valid index is
size - 1. - The size of a mutable list changes as you add and remove items.