androidengineers.Book a session

Collections and Data Structures

Arrays and Array Operations

article15 minMedium

Arrays have fixed size and mutable elements

Use an array when fixed-size indexed storage fits the problem or an API requires one. Specialized arrays such as IntArray avoid representing each element as a generic boxed integer on JVM.

fun main() {
    val minutes = intArrayOf(15, 25, 50)
    minutes[0] = 20
    val copy = minutes.copyOf()
    copy[1] = 30
    check(minutes[1] == 25)
    check(!minutes.contentEquals(copy))
    println(minutes.contentToString())
}

Assigning the array reference to another variable does not copy it. Use contentEquals for element comparison; ordinary array equality does not compare all elements as list equality does. copyOf copies the outer array, so arrays of mutable objects still share those elements.

Bounds remain your responsibility when indexing. Prefer indices or element iteration when possible.

Exercise

Calculate the maximum study duration in an IntArray, defining behavior for an empty array. Compare a manual loop with maxOrNull().

Check: verify one-element, all-equal, and empty arrays; do not assume index zero always exists.

Reference: Arrays

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Arrays and Array Operations | Kotlin Core Programming | Android Engineers