如何在Kotlin中用值初始化陣列?
陣列是一種資料結構,它包含一定數量的相同型別的值或資料。在這種資料結構中,每個元素都可以使用陣列索引訪問,陣列索引通常從“0”開始。
在Kotlin中,可以使用函式**arrayOf()**或使用Array建構函式建立陣列。
關於Kotlin中陣列的重要說明:
陣列按記憶體位置順序儲存。
所有陣列元素都可以使用其索引訪問。
陣列是可變的。
在傳統的程式設計中,大小通常與初始化一起宣告,因此我們可以得出結論,它們的大小是固定的。
示例
在這個例子中,我們將宣告一個科目陣列,並列印其值。
fun main() { // Declaring an array using arrayOf() val sampleArray= arrayOf("Java","C", "C++","C#", "Kotlin") // Printing all the values in the array for (i in 0..sampleArray.size-1) { // All the element can be accessed via the index println("The Subject Name is--->"+sampleArray[i]) } }
輸出
它將生成以下輸出:
The Subject Name is--->Java The Subject Name is--->C The Subject Name is--->C++ The Subject Name is--->C# The Subject Name is--->Kotlin
示例——使用Array建構函式
在Kotlin中,也可以使用陣列建構函式宣告陣列。此建構函式將採用兩個引數;一個是陣列的大小,另一個是接受元素索引並返回該元素初始值的函式。
在這個例子中,我們將看到如何使用陣列建構函式的內建功能來填充陣列並在應用程式中進一步使用相同的值。
示例
fun main() { // Declaring an array using arrayOf() val sampleArray= arrayOf("Java","C", "C++","C#", "Kotlin") // Printing all the values in the array for (i in 0..sampleArray.size-1) { // All the element can be accesed via the index println("The Subject Name is--->"+sampleArray[i]) } // Using Array constructor val myArray = Array(5, { i -> i * 1 }) for (i in 0..myArray.size-1) { println(myArray[i]) } }
輸出
它將生成以下輸出:
The Subject Name is--->Java The Subject Name is--->C The Subject Name is--->C++ The Subject Name is--->C# The Subject Name is--->Kotlin 0 1 2 3 4
廣告