Similar to other programming languages, arrays in Kotlin provide the ability to store and manage an ordered collection of elements of the same data type, such as a list of numbers, characters, or objects. They enable structured and organized storage of data as well as efficient access to individual elements via an index. Arrays are used in many use cases, from simple lists to tables to more complex multidimensional data structures. In Kotlin, arrays are objects that have the specially designed data type Array have.
The main properties of arrays in Kotlin are:
Same data type of included elements: This means that all objects within an array must have the same data type. For example just Int, String or Double etc., for example a combination of Int and String would lead to a program error.
In order to specify the data type for the elements within an array, the type of objects contained is specified in angle brackets after the array type when declaring an array. The following example creates an array of Int-Values created:
val arrayOfNumbers: Array<Int> // 'arrayOfNumbers' ist Variablenname. 'Array' ist Datentyp der Variable. '<Int>' bedeutet, dass das Array ausschließlich Werte des Datentyps 'Int' speichern kann.
The next step is to use the built-in function arrayOf() a row of Int-passing values to array:
val arrayOfNumbers: Array<Int> = arrayOf(1, 2, 3, 4, 5) // Es wird ein Array mit dem Namen 'arrayOfNumbers' vom Typ 'Array<Int>' deklariert und gleichzeitig mit Hilfe der Funktion 'arrayOf()' mit den Int-Werten 1, 2, 3, 4 und 5 initialisiert.
val arrayOfNumbers2: Array<Int> = arrayOf(1, 2, 3, 4, "Tom") // Der Versuch, ein Element vom Typ String hinzuzufügen, führt zu einem Fehler.
Indexed items: The elements in an array are indexed, meaning they have a specific position within the array that can be accessed via the associated index. Indexing of arrays starts at 0, i.e. the first element has the index 0, the second element the index 1, the third the index 2 and so forth. The index is given in square brackets. Let's look at our previous example:
fun main() {
val arrayOfNumbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
println(arrayOfNumbers[0]) // Hier wird der Wert des Elements mit Index '0' ausgegeben, also '1'.
println(arrayOfNumbers[1]) // 2
println(arrayOfNumbers[4]) // 5
arrayOfNumbers[0] = 44 // Element mit Index '0' wird geändert von '1' auf '44'
println(arrayOfNumbers[0]) // 22
}
Fixed size: Arrays have a fixed size, which is set when they are created. Once created, the size of an array cannot be changed. In the example below we are trying an additional element with index 5 add to the array:
fun main() {
val arrayOfNumbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
arrayOfNumbers[5] = 66 // Anweisung, um ein Element mit Index '5' und mit dem Wert '66' dem Array 'arrayOfNumbers' hinzufügen.
// Es wird Fehler 'Index 5 out of bounds for length 5' ausgegeben, da die Größe eines Arrays nicht verändert werden darf.
println(arrayOfNumbers[5])
}
To create an array in Kotlin you can also use the Constructor of class Array use which takes two parameters. The first parameter specifies the size of the array while the second parameter specifies the Initialization lambda contains. The initialization lambda is an expression that is executed for each element of the array and calculates the initial value for that element.
fun main() {
val arrayOfNumbers: Array<Int> = Array(3, {2*5}) // Parameter '3' definiert die Arraygröße, also das Array hat 3 Elemente.
// Der Ausdruck '{2*5}' wird für jedes Element des Arrays ausgeführt.
// Somit besteht das Array aus 3 Elementen mit dem Wert '10' [10. 10. 10].
for (element in arrayOfNumbers) {
println(element) // 10, 10, 10
}
}
The Initialization lambda can also contain more complex expressions and therefore carry out more sophisticated calculations.
fun main() {
var i:Int = 1
val arrayOfNumbers: Array<Int> = Array(5, {i++ * 2})
for (element in arrayOfNumbers) {
println(element) // 2, 4, 6, 8, 10
}
}
Iterating over arrays in Kotlin
In Kotlin, you can iterate through arrays and access their elements in various ways. One possibility is to have one for loop to use. Example:
fun main() {
val arrayOfNames: Array<String> = arrayOf("Tom", "Jerry", "Anna", "Frank", "Mandy")
for (name in arrayOfNames) {
println(name)
}
}
Another possibility is as part of a for loop to use the index as a running variable to iterate through the elements of an array one after the other.
fun main() {
val arrayOfNames: Array<String> = arrayOf("Tom", "Jerry", "Anna", "Frank", "Mandy")
for (i in arrayOfNames.indices) {
println("Name at index $i is ${arrayOfNames[i]}")
}
}
A slim alternative is to use the forEach() function, which performs an action on each element in the array.
fun main() {
val arrayOfNumbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
arrayOfNumbers.forEach { println(it) }
}
The function forEach lists the specified lambda expression (lambda function) for each element of the array, passing each element as an argument to the lambda expression. The word it in the Lambda function represents the current element to which the action is applied within the function.
Comment: The key word it In Kotlin, stands for an implicit name of the individual parameter in a Lambda function. If a Lambda function has a single parameter, the parameter name can be omitted and the implicit one instead it should be used.
Check if an element exists in an array
Let's assume we have the task of checking an array for the presence of the name “Jerry” to check. We have two options for this. Option number 1 is to use the in operators:
fun main() {
val arrayOfNames: Array<String> = arrayOf("Tom", "Jerry", "Anna", "Frank", "Mandy")
if ("Jerry" in arrayOfNames) {
println("The name 'Jerry' is included")
} else {
println("The name 'Jerry' is not included")
}
}
It is also possible to use a loop to iterate over all the elements of the array one by one and check whether each element corresponds to the element you are looking for. Example:
fun main() {
val arrayOfNames: Array<String> = arrayOf("Tom", "Jerry", "Anna", "Frank", "Mandy")
for (name in arrayOfNames) {
if (name == "Jerry") {
println("The name 'Jerry' is included")
break
}
}
}
Special functions for initializing arrays for primitive data types
In Kotlin, there is a special array type for each primitive data type. This includes BooleanArray, ByteArray, ShortArray, IntArray, LongArray, CharArray, FloatArray and DoubleArray. These special array types allow the creation of arrays for the respective data type, making data handling and processing easier.
val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) // Initialisierung des Arrays namens 'intArray' mithilfe der Funktion intArrayOf() und mit festzugewiesenen Int-Werten 1, 2, 3, 4, 5
val longArray: LongArray = longArrayOf(1L, 2L, 3L)
val floatArray: FloatArray = floatArrayOf(1.0f, 2.0f, 3.0f)
val doubleArray: DoubleArray = doubleArrayOf(1.0, 2.0, 3.0)
val charArray: CharArray = charArrayOf('a', 'b', 'c')
val booleanArray: BooleanArray = booleanArrayOf(true, false, true)
Initialization of these arrays can be done either by explicitly assigning values, as in the examples above, or by using constructors defined for the specific array types.
val intArray = IntArray(7) // Int-Array mit der Länge '7' und dem Standardwert '0'
val longArray = LongArray(3) // Long-Array mit der Länge '3' und dem Standardwert '0'
val floatArray = FloatArray(2) // Float-Array mit der Länge '2' und dem Standardwert '0.0'
val doubleArray = DoubleArray(4) // Double-Array mit der Länge '4' und dem Standardwert '0.0'
val charArray = CharArray(6) // Char-Array mit der Länge '6' und dem Standardwert '\u0000'
val booleanArray = BooleanArray(3) // Boolean-Array mit der Länge '3' und dem Standardwert 'false'
val intArray = IntArray(7) { -1 } // Int-Array mit der Länge '7' und dem Standardwert '-1'
val longArray = LongArray(3) { 100L } // Long-Array mit der Länge '3' und dem Standardwert '100L'
val floatArray = FloatArray(2) { 1.0f } // Float-Array mit der Länge '2' und dem Standardwert '1.0f'
val doubleArray = DoubleArray(5) { 3.14 } // Double-Array mit der Länge '5' und dem Standardwert '3.14'
val charArray = CharArray(6) { '!' } // Char-Array mit der Länge '6' und dem Standardwert '!'
val booleanArray = BooleanArray(4) { true } // Boolean-Array mit der Länge '4' und dem Standardwert 'true'
Multidimensional arrays
Previously we only looked at one-dimensional arrays, which can be thought of as a sequence or row of values.
// Beispiele von eindimesionalen Arrays
val arrayOfIntegers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
val arrayOfNames: Array<String> = arrayOf("Tom", "Max", "Anna", "Jerry", "Jack")
However, there are several use cases in software development that require the representation and processing of more complex, multi-dimensional data structures. Some of the most common and well-known usage scenarios for multidimensional data organization are: mapping tables and matrices with numbers to perform calculations or representing pixel values in images as well as volume values in 3D models. To store and process such data structures in Kotlin multidimensional arrays .
Multidimensional arrays in Kotlin are data structures consisting of nested arrays that organize data into multiple dimensions or levels. They can be thought of as arrays of arrays.
For example, a two-dimensional array (2D array) is like a table in which data is arranged in rows and columns.
fun main() {
// Erstellt ein 2D-Array mit 3 Zeilen und 3 Spalten mit Initialwerten '0'
val matrix = Array(3) { Array(3) { 0 } }
// Füllt das Array mit Werten
matrix[0] = arrayOf(1, 2, 3)
matrix[1] = arrayOf(4, 5, 6)
matrix[2] = arrayOf(7, 8, 9)
// Um auf die Elemente von Unterarrays in einem zweidimensionalen Array zuzugreifen,
// sind zwei Indizes erforderlich. Mit dem ersten Index wird die Zeile abgerufen und
// mit dem zweiten Index die Spalte innerhalb dieser Zeile.
val number1 = matrix[1][2] // Zeile mit Index '1', Spalte mit Index '2'
println(number1) // Ausgabe '6'
val number2 = matrix[2][0] // Zeile mit Index '1', Spalte mit Index '2'
println(number2) // Ausgabe '7'
}
It is also possible to loop through two-dimensional arrays using two nested loops.
fun main() {
// Erstellt ein 2D-Array mit 3 Zeilen und 3 Spalten mit Initialwerten '0'
val matrix = Array(3) { Array(3) { 0 } }
// Füllt das Array mit Werten
matrix[0] = arrayOf(1, 2, 3)
matrix[1] = arrayOf(4, 5, 6)
matrix[2] = arrayOf(7, 8, 9)
// Gibt das Array aus
for (row in matrix) {
for (value in row) {
print("$value ")
}
println()
}
}
A three-dimensional array (3D array) is like a stack of tables on top of each other and can be created by nesting an array of 2D arrays.
fun main() {
// Erstellt ein 3D-Array mit 2 Schichten, 3 Zeilen und 3 Spalten
val array3D = Array(2) { Array(3) { Array(3) { 0 } } }
// Füllt das 3D-Array mit Werten
array3D[0] = arrayOf(
arrayOf(1, 2, 3),
arrayOf(4, 5, 6),
arrayOf(7, 8, 9)
)
array3D[1] = arrayOf(
arrayOf(10, 11, 12),
arrayOf(13, 14, 15),
arrayOf(16, 17, 18)
)
// Um auf die Elemente von Unterarrays in einem dreidimensionalen Array zuzugreifen,
// sind drei Indizes erforderlich. Mit dem ersten Index wird das Array angesprochen,
// mit dem zweiten Index die Zeile innerhalb des Array abgerufen und
// mit dem dritten Index die Spalte innerhalb dieser Zeile.
val number1 = array3D[0][2][0] // Array mit Index '0', Zeile mit Index '2', Spalte mit Index '0'
println(number1) // Ausgabe '7'
val number2 = array3D[1][1][1] // Array mit Index '1', Zeile mit Index '1', Spalte mit Index '1'
println(number2) // Ausgabe '14'
println() // Leere Zeile
// Gibt das 3D-Array aus
for (layer in array3D) {
for (row in layer) {
for (value in row) {
print("$value ")
}
println()
}
println("----")
}
}
In the examples above, 2D and 3D arrays have been created and filled with values. Note that these examples use fixed-size arrays, but you can also use ArrayLists to create dynamic, multidimensional arrays. We will look at this topic in detail later in the tutorial.