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