Arrays

dakshdeepHERE's avatar
Published Jan 20, 2023
Contribute to Docs

Arrays are collections of items of the same data type with 0-based indexing that are stored at contiguous memory locations.

Syntax

// Array class instance
arrayOne = arrayOf<Type>(values)
arrayTwo = Array(size) iteratorFunction

// Array of primitive types
arrayThree: TypeArray = typeArrayOf(values)
arrayFour = TypeArray(size) iteratorFunction

Instances of the Array class are created in either of the following ways:

  • The arrayOf() function accepts an optional <Type> and a comma-separated list of values.
  • With the Array() class constructor that accepts a size parameter and an iteratorFunction for populating the array.

Arrays of primitive type values can also be created:

  • In lieu of TypeArray, actual class names (e.g., IntArray) should be used for typing or constructing the new array.
    • The TypeArray() constructor uses a size parameter as well as an iteratorFunction.
  • The typeArrayOf() function uses a list of values to create an array of a certain data type (e.g., intArrayOf()).

Example

The following example uses the Array() class constructor to create and populate a num array. The elements are then printed:

fun main() {
val num = Array(5, {i-> i*1})
for (i in 0..num.size - 1) {
print(" " + num[i])
}
println()
}

This prints the following output:

0 1 2 3 4

Arrays

.forEach()
Iterates over elements in a collection and performs a specified action on each element, without producing a new collection.
.get()
Returns the element located at a given position in an array.
.indices
Returns a range indicating the valid indices in an array.
.map()
Transforms elements in a collection by applying a specified transformation function, resulting in a new collection with the transformed values.
.reverse()
Reverses the order of the elements in-place in a specified array.
.size
Calculates the number of elements in an array.
.slice()
Creates a new list containing elements from the specified range or indices of an array.
.sort()
Returns a sorted array, modifying the original array in-place to arrange its elements in ascending order.
arrayOf()
Creates a new array containing the specified elements.
arrayOfNulls()
Creates an array of a specified size with all elements initialized as null.

All contributors

Contribute to Docs

Learn Kotlin on Codecademy