# Kotlin數組

#### 數組的構造函數

``Array(size: Int, init: (Int) -> T)``

Kotlin數組聲明 - 使用arrayOf()函數

``````var myArray1 = arrayOf(1,10,4,6,15)
var myArray2 = arrayOf<Int>(1,10,4,6,15)
val myArray3 = arrayOf<String>("Ajax","Prake","Michel","John","Curry")
var myArray4= arrayOf(1,10,4, "Ajax","Prake")``````

Kotlin數組聲明 - 使用intArrayOf()函數

``var myArray5: IntArray = intArrayOf(5,10,20,12,15)``

#### 修改和訪問數組的元素

Kotlin數組有`set()``get()`函數，可以分別直接修改和訪問數組的特定元素。

Kotlin數組set()函數示例

``````fun main(args: Array<String>) {
val array1 = arrayOf(1,2,3,4)
val array2 = arrayOf<Long>(11,12,13,14)
array1.set(0,5)
array1[2] = 6

array2.set(2,10)
array2[3] = 8

for(element in array1){
println(element)
}
println()
for(element in array2){
println(element)
}
}``````

``````5
2
6
4

11
12
10
8``````

Kotlin數組get()函數示例

``````fun main(args: Array<String>) {
val array1 = arrayOf(1,2,3,4)
val array2 = arrayOf<Long>(11,12,13,14)
println(array1.get(0))
println(array1[2])
println()
println(array2.get(2))
println(array2[3])
}``````

``````1
3

13
14``````

Kotlin數組示例1：

``````fun main(args: Array<String>){
var myArray = Array<Int>(5){0}

for(element in myArray){
println(element)
}
}``````

``````0
0
0
0
0``````

Kotlin數組示例2：

``````fun main(args: Array<String>){
var myArray = Array<Int>(5){0}

myArray[1]= 10
myArray[3]= 15

for(element in myArray){
println(element)
}
}``````

``````0
10
0
15
0``````

Kotlin數組示例3 - 使用arrayOf()和intArrayOf()函數：
Kotlin中的數組也可以使用庫函數聲明，例如`arrayOf()``intArrayOf()`等。下面來看看使用`arrayOf()``intArrayOf()`函數的數組示例。

``````fun main(args: Array<String>){
val name = arrayOf<String>("Ajax","Prake","Michel","John","Sumit")
var myArray2 = arrayOf<Int>(1,10,4,6,15)
var myArray3 = arrayOf(5,10,20,12,15)
var myArray4= arrayOf(1,10,4, "Ajax","Prake")
var myArray5: IntArray = intArrayOf(5,10,20,12,15)

for(element in name){
println(element)
}

println()
for(element in myArray2){
println(element)
}
println()
for(element in myArray3){
println(element)
}
println()
for(element in myArray4){
println(element)
}
println()
for(element in myArray5){
println(element)
}

}``````

``````Ajax
Prake
Michel
John
Sumit

1
10
4
6
15

5
10
20
12
15

1
10
4
Ajax
Prake

5
10
20
12
15``````

Kotlin數組示例4

``````fun main(args: Array<String>){
var myArray5: IntArray = intArrayOf(5,10,20,12,15)

myArray5[6]=18 // ArrayIndexOutOfBoundsException
for(element in myArray5){
println(element)
}
}``````

``````Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at HelloWorldKt.main(HelloWorld.kt:4)``````

Kotlin數組例5 - 遍歷使用範圍：

``````fun main(args: Array<String>){
var myArray5: IntArray = intArrayOf(5,10,20,12,15)

for (index in 0..4){
println(myArray5[index])
}
println()
for (index in 0..myArray5.size-1){
println(myArray5[index])
}
}``````

``````5
10
20
12
15

5
10
20
12
15``````