- Kotlin 教程
- Kotlin - 首頁
- Kotlin - 概述
- Kotlin - 環境搭建
- Kotlin - 架構
- Kotlin - 基本語法
- Kotlin - 註釋
- Kotlin - 關鍵字
- Kotlin - 變數
- Kotlin - 資料型別
- Kotlin - 運算子
- Kotlin - 布林值
- Kotlin - 字串
- Kotlin - 陣列
- Kotlin - 範圍
- Kotlin - 函式
- Kotlin 控制流
- Kotlin - 控制流
- Kotlin - if...else 表示式
- Kotlin - when 表示式
- Kotlin - for 迴圈
- Kotlin - while 迴圈
- Kotlin - break 和 continue
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集合
- Kotlin - 對映
- Kotlin 物件和類
- Kotlin - 類和物件
- Kotlin - 建構函式
- Kotlin - 繼承
- Kotlin - 抽象類
- Kotlin - 介面
- Kotlin - 可見性控制
- Kotlin - 擴充套件
- Kotlin - 資料類
- Kotlin - 密封類
- Kotlin - 泛型
- Kotlin - 委託
- Kotlin - 解構宣告
- Kotlin - 異常處理
- Kotlin 有用資源
- Kotlin - 快速指南
- Kotlin - 有用資源
- Kotlin - 討論
Kotlin 陣列 - get() 函式
Kotlin 陣列的 get() 函式檢索指定索引位置的陣列元素,如果索引超出陣列範圍,則丟擲 IndexOutOfBoundsException 異常。此函式使用索引運算子呼叫。例如,value = arr[index]。
語法
以下是 Kotlin 陣列 get() 函式的語法:
operator fun get(index: Int): T
引數
此函式接受單個引數 index。它表示需要返回的元素的位置。
返回值
此函式根據指定索引位置的元素,返回陣列的指定型別的值。
示例 1
以下是一個基本示例,我們建立一個大小為 10 的陣列。然後我們使用 get() 函式顯示指定索引位置的元素:
import java.lang.Exception
fun main(args: Array<String>) {
var array = Array(10) { i -> i}
val index = 5
try {
val value = array.get(index)
println("The value at the index $index in the array is: $value ")
} catch (exception : Exception) {
println("Invalid index entered, size of the array is ${array.size}")
println(exception.printStackTrace())
}
}
輸出
以下是輸出:
The value at the index 5 in the array is: 5
示例 2
現在,讓我們建立一個另一個示例。在這種情況下,我們傳遞一個超出陣列大小的索引值,這將導致 IndexOutOfBoundsException 異常:
import java.lang.Exception
fun main(args: Array<String>) {
var array = Array(2) { init -> 1 }
val index = 3
try {
val value = array.get(index)
println("The value at the index $index in the array is: $value ")
} catch (exception : Exception) {
println("Invalid index entered, size of the array is ${array.size}")
println(exception.printStackTrace())
}
}
輸出
以下是輸出:
Invalid index entered, size of the array is 2 java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
示例 3
下面的示例建立一個大小為 10,包含不同型別的陣列。然後,它根據迭代計數賦值。然後我們使用 get() 獲取指定索引的值:
import java.lang.Exception
fun main(args: Array<String>) {
var array = Array(10) { i ->
if(i<3) {'c'}
else if(i<5) {"Hi"}
else {5}
}
val index = 3
try {
val value = array.get(index)
println("The value at the index $index in the array is: $value ")
} catch (exception : Exception) {
println("Invalid index entered, size of the array is ${array.size}")
println(exception.printStackTrace())
}
}
輸出
以上程式碼生成以下輸出:
The value at the index 3 in the array is: Hi
kotlin_arrays.htm
廣告