- 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 数组 - set() 函数
Kotlin 数组的 set() 函数将指定索引位置的数组元素设置为指定值,如果索引超出数组范围,则抛出 IndexOutOfBoundsException 异常。此函数使用索引运算符调用。例如,value = arr[index]。
语法
以下是 Kotlin 数组 set() 函数的语法:
operator fun set(index: Int, value: T)
参数
此函数接受以下参数
index. 表示需要设置值的元素的位置。
value. 表示需要在给定索引位置赋值的值。
返回值
此函数不返回任何值。
示例 1
以下是一个基本示例,我们创建了一个大小为 5 的数组。然后我们使用 set() 函数更改指定索引位置之前分配的值:
import java.lang.Exception
fun main(args: Array<String>) {
var array = Array(5) { i -> i}
val index = 3
try {
array.set(index, 4)
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: 4
示例 2
现在,让我们创建另一个示例。在这种情况下,我们传递了一个超出数组大小的索引值,这会导致 IndexOutOfBoundsException 异常:
import java.lang.Exception
fun main(args: Array<String>) {
var array = Array(2) { i -> 0 }
val index = 4
try {
array.set(index, 10)
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 4 out of bounds for length 2
示例 3
下面的示例创建一个大小为 10 且包含不同类型的数组。然后,它根据迭代计数分配值。然后我们使用 set() 更改指定索引值的元素:
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 = 2
try {
array.set(index, "tutorialspoint")
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 2 in the array is: tutorialspoint
kotlin_arrays.htm
广告