Start learning free

LESSON 111 OF 677 · ARRAYS I

Exceeding ArrayList Bounds in Kotlin

Lesson

When accessing ArrayList data with indices, the most common problem we can run into is exceeding the ArrayList's bounds.

Remember, the items of an ArrayList are indexed from 0 to size - 1. Any index which is not in this range is invalid.

When you try to access an item with an invalid index, Kotlin throws an error:

val myArray = mutableListOf(50, 40, 30)

// Valid indices: 0, 1, 2
println(myArray[0]) // Output: 50
println(myArray[2]) // Output: 30

// Invalid indices: 3, 30, -1
println(myArray[3]) // throws IndexOutOfBoundsException
println(myArray[30]) // throws IndexOutOfBoundsException
println(myArray[-1]) // throws IndexOutOfBoundsException

As programmers, we always want to make sure that we don't exceed one ArrayList's bounds in our programs.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check