Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Collections: Lists and Arrays | Control Flow and Collections
Android Development with Kotlin
course content

Зміст курсу

Android Development with Kotlin

Android Development with Kotlin

1. Kotlin Basics
2. Control Flow and Collections
3. Object-Oriented Programming in Kotlin

bookCollections: Lists and Arrays

It's not always convenient to store a large amount of data in different variables. That's why Kotlin, like any other programming language, has arrays.

An array is a collection of elements of the same type that can be accessed by indexing. Arrays in Kotlin are a bit different from those in other programming languages as they are invariant, meaning you cannot assign an array of one type to an array of another type.

Note

All elements in an array must be of the same data type. For example, a single array cannot contain both strings and numbers.

You can declare an array using the arrayOf function:

kt

Main

copy
1
val numbers = arrayOf(1, 2, 3, 4, 5)

Each of these elements is located at its own index, which we will now discuss.

Indexing

In arrays in almost any programming language, zero-based indexing is used. This means that indexes start at 0.

As you can see from the illustration, the first element is at index zero. The second element is at index one, and so on.

To determine the index of a specific element, we need to subtract one from the element's number (n - 1).

We use indexing to access elements in an array. Indexes allow us to do this.

Let's display the 1st and 3rd elements of the array we created:

kt

Main

copy
123456
fun main() { val numbers = arrayOf(1, 2, 3, 4, 5) val firstElement: Int = numbers[0] val thirdElement: Int = numbers[2] }

This way, we can use arrays to store many elements and access them by their indexes.

Using Loops with Arrays

In the previous chapter, I mentioned that the for loop works great with arrays and other collections of elements. So, let's see how we can iterate through an array of elements using this loop.

For this, we just need to use the following syntax:

kt

Main

copy
1234567
fun main() { val numbers = arrayOf(3, 1, 6, 4, 5) for (item in numbers) { println(item) } }

Here, the variable i created inside the loop is not an iterator but an item. That's why we named this variable item. So, when iterating through the array, we will work directly with the elements of the array, which we can access through the item variable.

Let's look at the illustration where this will become clearer:

From the illustration, you can see that during each iteration, the item variable takes the value of the array element corresponding to the iteration number.

Note

Don’t confuse the element number with the element index. When working with the for loop, we don't deal with indexes. The first element of the array is the element at index 0, so in the loop, the item variable holds the value of the FIRST element of the array.

If we want to access the array indexes, we need to use the indices property of arrays.

Here’s how it looks in the code:

kt

Main

copy
1234567
fun main() { val numbers = arrayOf(3, 1, 6, 4, 5) for (index in numbers.indices) { println("The value of the element at index $index is ${numbers[index]}.") } }

Now, the variable we created is an index, and inside the loop, we access both the indexes and the elements of the array.

Note

Essentially, this performs the same operation as in the previous loop variant because arrayName.indices returns an array of indexes, so we are just iterating over a different array, performing the same actions as before.

We can also create an array of strings and use the same operations with it.

For example, let’s create an array of fruits:

kt

Main

copy
1234567
fun main() { val fruits = listOf("apple", "banana", "cherry") for (index in fruits.indices) { println("Item at index $index is ${fruits[index]}") } }

I hope at this point we've covered what arrays are and how to use them, so let’s move on to another type of data collection—lists.

List

Lists are more flexible compared to arrays and are much easier to work with. Lists in Kotlin can be mutable or immutable. An immutable list is read-only, while a mutable list can be modified.

Let’s look at how to create these two types of lists:

kt

Main

copy
12345678910111213141516171819202122232425
fun main() { // Declared using the listOf function: val fruits = listOf("Apple", "Banana", "Cherry") // Elements cannot be added, removed, or modified. // Declared using the mutableListOf function: val vegetables = mutableListOf("Carrot", "Potato", "Tomato") // Elements can be added, removed, or modified: vegetables.add("Cucumber") vegetables.remove("Potato") vegetables[0] = "Broccoli" println("Fruits: ") for (fruit in fruits) { print("$fruit ") } println() // used to move on the next line println("Vegetables: ") for (vegetable in vegetables) { print("$vegetable ") } }

The code might seem a bit complex, but it's not difficult.

First, we create a list that cannot be changed. We use the listOf() method and specify the elements for the list inside it.

Next, we create a list that can be modified using the mutableListOf() method, and then immediately start modifying it. Lists can be modified using various methods such as add and remove.

Note

There are more methods for modifying and working with lists beyond adding or removing items, but we’ll cover those later as they’re not our focus right now.

After that, using two for loops, we print both lists to the screen to see how we implemented the changes.

An important note is that arrays can only store elements of one data type, whereas lists can store elements of different data types.

For example, let’s create and display a junk list with elements of completely different data types:

kt

Main

copy
12345678
fun main() { val junk = listOf("Apple", "Bob", false, "chef", 3.14, 293, "Nineteen", 11, true, true) println("List elements: ") for (item in junk) { print("$item ") } }

This way, we can conclude that lists and arrays are a simple and reliable way to store various data types, making them convenient.

1. What does the `arrayOf` function do in Kotlin?
2. How are elements accessed within an array in Kotlin?
3. Which of the following is true about lists in Kotlin?
What does the `arrayOf` function do in Kotlin?

What does the arrayOf function do in Kotlin?

Виберіть правильну відповідь

How are elements accessed within an array in Kotlin?

How are elements accessed within an array in Kotlin?

Виберіть правильну відповідь

Which of the following is true about lists in Kotlin?

Which of the following is true about lists in Kotlin?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2
some-alt