Arrays

dakshdeepHERE23 total contributions
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 ofvalues
. - With the
Array()
class constructor that accepts asize
parameter and aniteratorFunction
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 asize
parameter as well as aniteratorFunction
.
- The
- The
typeArrayOf()
function uses a list ofvalues
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
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.