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