Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
KotlinStrings, arrays and ranges

Arrays

Introduction to arrays

When you need to process multiple objects of the same type, you can save them in an array and then process together as a single unit. It is a very convenient approach if you do not know how many objects the program will process during runtime.

You may consider an array as a collection of elements of the same type. All elements are stored in the memory sequentially.

The collection provides one name for its elements. The possible number of elements to be stored is established when the array is created and cannot be changed. But a stored element can be modified at any time.

The picture below illustrates an array of five floating-point numbers. Each element has an integer index (0-4) to be accessed. Important, the first element has the index 0, the last element has the index equal array size - 1.

An array of five floating-point elements

We hope, you got a general idea of what array is. Now let's use it in Kotlin.

Creating an array with specified elements

Kotlin provides many types for representing arrays: IntArray, LongArray, DoubleArray, FloatArray, CharArray, ShortArray, ByteArray, BooleanArray. Each array store elements of the corresponding type (Int, Long, Double and so on). Note, there is no StringArray.

To create an array of a specified type, we should invoke a special function and pass all elements to be stored together:
  • intArrayOf creates IntArrays
  • charArrayOf creates CharArray;
  • doubleArrayOf creates DoubleArray;
  • and so on.
As an example, let's create three arrays:

val numbers = intArrayOf(1, 2, 3, 4, 5) // It stores 5 elements of the Int type
println(numbers.joinToString()) // 1, 2, 3, 4, 5

val characters = charArrayOf('K', 't', 'l') // It stores 3 elements of the Char type
println(characters.joinToString()) // K, t, l

val doubles = doubleArrayOf(1.25, 0.17, 0.4) // It stores 3 elements of the Double type
println(doubles.joinToString()) // 1.15, 0.17, 0.4

This code snippet prints three arrays:

1, 2, 3, 4, 5
K, t, l
1.25, 0.17, 0.4

The joinToString function converts an array to a string to be printed.

Creating an array with a specified size

To create an array with a specified size we should write its type and pass it after the type's name in round brackets (constructor):

val numbers = IntArray(5) // an array for 5 integer numbers
println(numbers.joinToString())

val doubles = DoubleArray(7) // an array for 7 doubles
println(doubles.joinToString())

These arrays with the predefined size filled by default values of the corresponding types (zeros for numeric types):

0, 0, 0, 0, 0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0

Despite the fact that the size of an array cannot be changed, the elements can be modified. Next, we will look at how to do this.

The size of an array

Regardless of how an array was created, it always has a size (the number of elements). To obtain it we should take the value of the size property (it is a number of the Int type).

val numbers = intArrayOf(1, 2, 3, 4, 5)
println(numbers.size) // 5 

Remember, the size of an array cannot be changed after creation.

Accessing elements

The values of elements of an array can be changed. To set (get) a value to (from) array the index is used.

Set the value by the index:

array[index] = elem

Get the value by the index

val elem = array[index]

Indexes of an array are numbers from 0 (the first element) to array.size - 1 (the last element) inclusive.

Here is an example with a 3-element array of integers.

val numbers = IntArray(3) // numbers: 0, 0, 0

numbers[0] = 1 // numbers: 1, 0, 0
numbers[1] = 2 // numbers: 1, 2, 0
numbers[2] = numbers[0] + numbers[1] // numbers: 1, 2, 3

println(numbers[0]) // 1, the first element
println(numbers[2]) // 3, the last element

Let's explain the code above. First, there is an array with three elements is created. By default, all elements are equal to 0. Then, the value 1 is assigned to the first element of the array by the index 0. Then, the value 2 is assigned to the second element of the array by the index 1. After, the value 3 (the sum of 1 and 2) is assigned to the last element of the array by the index 2. Then we print the first and the last element of the 3-element array.

Note, if we try to access a non-existing element by an index then the program will fail with an exception. Let's try to get fourth element (with the index 3) of the considered array numbers.

val elem = numbers[3]

The program throws ArrayIndexOutOfBoundsException.

Be careful while indexing elements of an array.

As you already know, the last element has the index that equals array size - 1. Let's access the last and the previous element.

val strings = arrayOf("abc", "cdf", "efg")

val last = strings[strings.size - 1] // "efg"
val prelast = strings[strings.size - 2] // "cdf"

Kotlin provides several convenient ways to access the first and the last element of an array as well as the last index:

println(greeting.first())   // 'H'
println(greeting.last())    // 'o'
println(greeting.lastIndex) // 4

Use this approach to make your code more readable and prevent accessing unexisting indexes.

Comparing arrays

To compare two arrays, invoke the contentEquals function of an array, passing another one as the argument. This function returns true when two arrays contain exactly the same elements (in the same order), otherwise, it returns false.
val numbers1 = intArrayOf(1, 2, 3, 4)
val numbers2 = intArrayOf(1, 2, 3, 4)
val numbers3 = intArrayOf(1, 2, 3)

println(numbers1.contentEquals(numbers2)) // true
println(numbers1.contentEquals(numbers3)) // false

Do not use the operators == and != for comparing arrays. They do not compare contents of arrays.

Conclusion

We considered what is an array and what basic operations it provides. Remember the following points:

  • an array is a collection of elements accessed by indexes;
  • the first element of an array has the index 0;
  • an array has a size;
  • it is possible to modify an element of an array by its index;
  • Kotlin has arrays to different types such as IntArray, CharArray, DoubleArray and so on.
How did you like the theory?
Report a typo