Kotlin Array (original) (raw)
Array is one of the most fundamental data structures in practically all programming languages. The idea behind an array is to store multiple items of the same data type, such as an _integer or _string, under a single variable name. Arrays are used to organize data in programming so that a related set of values can be easily sorted or searched.
Here are some basic properties of arrays.
- They are stored in contiguous memory locations.
- They can be accessed programmatically through their indexes (array[1], array[0], etc.)
- They are mutable.
- Their size is fixed.
To learn more about the array data structure, check out the Array tutorials.
Creating an array
In Kotlin, arrays are not a native data type, but a mutable collection of similar items, which are represented by the Array class.
There are **two ways to define an array in Kotlin.
**Using the arrayOf()
function
We can use the library function arrayOf()
to create an array by passing the values of the elements to the function.
**Syntax:
val num = arrayOf(1, 2, 3, 4) //implicit type declaration
val num = arrayOf(1, 2, 3) //explicit type declaration
**Kotlin program for creating an array using the arrayOf() and arrayOf functions
Kotlin `
fun main() { // declaring an array using arrayOf() val arrayname = arrayOf(1, 2, 3, 4, 5) for (i in 0..arrayname.size-1) { print(" "+arrayname[i]) } println() // declaring an array using arrayOf val arrayname2 = arrayOf(10, 20, 30, 40, 50) for (i in 0..arrayname2.size-1) { print(" "+arrayname2[i]) } }
`
**Output:
1 2 3 4 5
10 20 30 40 50
**Using the Array constructor
Since Array is a class in Kotlin, we can also use the Array constructor to create an array. The constructor takes **two parameters:
- The size of the array, and
- A function that accepts the index of a given element and returns the initial value of that element.
**Syntax:
val num = Array(3, {i-> i*1})
In the above example, we pass the size of the array as 3 and a lambda expression which initializes the element values from 0 to 9.
**Kotlin program for creating an array using a constructor
Kotlin `
fun main() { val arrayname = Array(5, { i -> i * 1 }) for (i in 0..arrayname.size-1) { println(arrayname[i]) } }
`
**Output:
0
1
2
3
4
Apart from these, Kotlin also has some **built-in factory methods to create arrays of primitive data types, such as byteArray, intArray, shortArray, etc. These classes do not extend the Array class; however, they implement the same methods and properties. For example, the factory method to create an integer array is:
val num = intArrayOf(1, 2, 3, 4)
Other factory methods available for creating arrays:
- byteArrayOf()
- charArrayOf()
- shortArrayOf()
- longArrayOf()
Accessing and modifying arrays
So far, we have seen how to create and initialize an array in Kotlin. Now, let’s see how to access and modify them. Again, there are **two ways of doing this:
**Using get()
and set()
methods
As you know, an array in Kotlin is a **class. Therefore, we can access the data of a class object via its member functions. The get()
and set()
functions are said to be member functions. The get()
method takes a single parameter—the index of the element and returns the value of the item at that index.
**Syntax:
val x = num.get(0)
The set()
method takes 2 parameters: the index of the element and the value to be inserted.
**Syntax:
num.set(1, 3)
The above code sets the value of the second element in the array to 3
**Using the index operator [ ]
The [ ]
operator can be used to access and modify arrays. To access an array element, the syntax would be:
val x = num[1]
This will assign the value of the second element in _num to _x. To modify an array element, we should do:
num[2] = 5;
This will change the value of the third element in the num array to 5.
**Note: Internally, the index operator or [ ] is an overloaded operator (see operator overloading) and only stands for calls to the get()
and set()
member functions. Here is a working example of Kotlin array manipulation in which we create an array, modify its values, and access a particular element:
Kotlin `
fun main() { // declare an array using arrayOf() val num = arrayOf(1, 2, 3, 4, 5)
num.set(0, 10) // set the first element equal to 10
num.set(1, 6) // set the secondelement equal to 6
println(num.get(0)) // print the first element using get()
println(num[1]) // print the second element using []
}
`
**Output:
10
6
Traversing Arrays
One important property of an array is that it can be traversed programmatically, and each element in the array can be manipulated individually. Kotlin supports few powerful ways to traverse array. The simplest and most commonly used idiom when it comes to traversing an array is to use the for-loop..
**Syntax:
for(i in num.indices){
println(num[i])
}
**Kotlin program for array traversal using a for loop
Kotlin `
// Traversing an array fun main() { val num = arrayOf(1, 2, 3, 4, 5) num.set(0, 10) num.set(1, 6) for (i in num.indices) { println(num[i]) } }
`
**Output:
10
6
3
4
5
Alternatively, we can use the range to achieve the same effect. In Kotlin, a **range is an interval between two values (start and end) and can be created using the ****(..)** operator. Traversal through the range can then be done using the **in keyword.
**Syntax for range:
for (i in 0..10){
println(i)
}
The range of elements in an array is defined from 0 to size-1. So, to traverse an array using range, we run a loop from 0 to size-1 on the array name.
**Kotlin program for array traversal using range
Kotlin `
// Traversing an array fun main() { val arrayname = arrayOf(1, 2, 3, 4, 5) for (i in 0..arrayname.size-1) { println(arrayname[i]) } }
`
**Output:
1
2
3
4
5
Another arguably less tedious, way to do the above is using the foreach loop.
**Syntax:
arrayname.forEach({index->println(index)})
**Kotlin program of array traversal using a foreach loop
Kotlin `
// Traversing an array fun main() { val arrayname = arrayOf(1, 2, 3, 4, 5) arrayname.forEach({ index -> println(index) }) }
`
**Output:
1
2
3
4
5