# Kotlin可變數組

Array是`Int``String`等類似數據的集合。Kotlin中的數組具有固定大小的可變性。 這意味着可以對數組元素執行讀寫操作。

``var myArray = Array<Int>(5){0}``

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","Sumit")
var myArray4= arrayOf(1,10,4, "Ajax","Prake")``````

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

#### 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","Yiibai","Maxsu")
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("Array 1 => ")
for(element in myArray2){
println(element)
}
println("Array 2 => ")
for(element in myArray3){
println(element)
}
println("Array 3 => ")
for(element in myArray4){
println(element)
}
println("Array 4 => ")
for(element in myArray5){
println(element)
}

}``````

``````Ajax
Prake
Michel
Yiibai
Maxsu
Array 1 =>
1
10
4
6
15
Array 2 =>
5
10
20
12
15
Array 3 =>
1
10
4
Ajax
Prake
Array 4 =>
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 ArrayListKt.main(Array.kt:4)``````

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

Kotlin的數組元素也使用索引範圍(`minValue..maxValue`)或(`maxValue..minvalue`)遍歷。 讓我們看一個使用範圍遍歷數組的示例。

``````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``````